Rafi Kamal Rafi Kamal - 4 months ago 280
Android Question

Android onRequestPermissionsResult is getting called only on Activity but not on Fragment

I have an Activity which contains a fragment. I am requesting contact permission from the activity as follows:

ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_CONTACTS}, REQUEST_CODE_PERMISSION);


and from fragment I am requesting camera permission like this:

requestPermissions(new String[] {Manifest.permission.CAMERA}, REQUEST_CODE_PERMISSION);


I have
onRequestPermissionsResult
method on both the fragment and the activity. The problem is, even if I request permission from the fragment, the
onRequestPermissionsResult
from the activity gets called. The
onRequestPermissionsResult
from the fragment doesn't get called (but it gets called if I remove
onRequestPermissionsResult
from the activity). Is there any way to appropriate
onRequestPermissionsResult
method?

Answer

Be sure to call super.onRequestPermissionsResult(...) when you overrides the method in your Activity.

That said, one other way to solve this is to manually notify the Fragments that you have within your activity:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    final List<Fragment> fragments = getSupportFragmentManager().getFragments();
    if (fragments != null) {
        for (Fragment fragment : fragments) {
            fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

..and just have your fragments respond by doing the appropriate action if the requestCode sent is theirs.

Comments