Some users in my app get this error:
Caused by: java.lang.ArrayIndexOutOfBoundsException: at
com.file.gt.MainActivity.onRequestPermissionsResult
(MainActivity.java:234) at android.app.Activity.requestPermissions
(Activity.java:5323) at com.file.gt.MainActivity.onCreate
(MainActivity.java:85) at android.app.Activity.performCreate
(Activity.java:8114) at android.app.Activity.performCreate
(Activity.java:8098) at
android.app.Instrumentation.callActivityOnCreate
(Instrumentation.java:1309) at
android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:3480)
It occurs only sometimes, with some users.
I have this in my app:
private final String [] permissions = {
"android.permission.RECORD_AUDIO",
"android.permission.READ_PHONE_STATE"
};
int requestCode = 200;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(permissions[0]) == PackageManager.PERMISSION_DENIED ||
checkSelfPermission(permissions[1]) == PackageManager.PERMISSION_DENIED) {
requestPermissions(permissions, requestCode);
}
}
and this:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
recreate(); // 234
}
else {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle(getString(R.string.alert_title));
alertDialog.setMessage(getString(R.string.alert_text));
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
(dialog, which) -> dialog.dismiss());
alertDialog.show();
}
}
Any ideas what is wrong and what I’m doing wrong?
Thanks.
2
Answers
//user this code to check
When you get an
ArrayIndexOutOfBoundsException
it means you are accessing an array index outside the array size. Your stack trace says it happens inonRequestPermissionsResult
, and the only array you access there isgrantResults
.What can sometimes happen is that
grantResults
is empty inonRequestPermissionsResult
if the user declines the permissions, so you should check its size before accessing its membersAlternately, if you use the new
registerForActivityResult
approach you can get around this entirely. Have a look here for more info, or here for an example use.