java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode

Solution 1:

You get this exception only in android.support.v4.app.FragmentActivity and not when you use android.app.Activity.

startActivityForResult() in FragmentActivity requires the requestCode to be of 16 bits, meaning the range is from 0 to 65535.

Also, validateRequestPermissionsRequestCode in FragmentActivity requires requestCode to be of 16 bits, meaning the range is from 0 to 65535.

For more info(if you want to see the source code) : https://stackoverflow.com/a/33331459/4747587

Solution 2:

If you're using ActivityResult APIs, add this dependency to fix this issue:

implementation "androidx.fragment:fragment:1.3.4"

Solution 3:

It is also good to mention that this may happen if you use a number greater than 2^16 / 2 (which is 32768), so there's basically 2^15 options to not to screw this up.

Explanation: 16 bits can represent one of 65536 numbers, however, half of them are negative.