Photo by John Moeses Bauan on Unsplash

Why am I getting a different request code back?

This was a question I searched for the answer to after the seemingly strange occurrence that the request code I was getting back was a completely different number.

The short explanation of what I was trying to accomplish was that I was requesting some camera permissions, then handling the result in onRequestPermissionsResult(). The struggle came in when the requestCode was different than the one I sent.

I admittedly went down the rabbit hole to try to figure out why this might be happening, using the debugger to follow the code all the way down, and I found this in FragmentActivity:

requestPermissionsFromFragment() method from FragmentActivity

I saw that in the requestPermissionsFromFragment() method the request code was being changed with ((requestIndex + 1) << 16) + (requestCode & 0xfff). When applying this to my request code, I found it gave me the erroneous number I was getting instead!

Surely there must be a reason for this. Any other time I request permissions I get the correct request code back, but this time I’m getting this converted number.

I eventually figured out why. To understand better, let me explain the architecture of my situation.

As you might expect from ending up in the FragmentActivity, I was working with Fragments, two of them to be specific. FragmentA would show FragmentB. FragmentB would then request the permissions for the camera, and be dismissed. Because FragmentB no longer existed, I would handle the results in FragmentA. This was the root of my issue.

The solution

I eventually found this answer on StackOverflow:

This was exactly what I was seeing! From my understanding, whenever you request permissions from a Fragment or NestedFragment, it calls to request the permissions on the host of that Fragment all the way up the chain, modifying the the request code at each layer. Then on the way back down with the result, it changes it back at each layer again. Because I was handling the result in a different Fragment than the one I requested it in, it was not being changed all the way back to it’s original value.

Once I ensured that the same Fragment that requested the permissions was the one handling it, I was golden! In this situation, it required passing a reference of it to the second Fragment, but it worked out.

Remember this: Always handle onRequestPermissionsResult() in the same Activity or Fragment that requested the permissions.