I'm starting a new Activity from my Fragment with
startActivityForResult(intent, 1);
and want to handle the result in the Fragment's parent Activity:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult, requestCode: " + requestCode + ", resultCode: " + resultCode); if (requestCode == 1) { // bla bla bla } }
The problem is that I never got the requestCode
I've just posted to startActivityForResult()
.
I got something like 0x40001
, 0x20001
etc. with a random higher bit set. The docs don't say anything about this. Any ideas?
activity:activity-ktx to 1.2. 0 . It has deprecated startActivityForResult in favour of registerForActivityResult . It was one of the first fundamentals that any Android developer has learned, and the backbone of Android's way of communicating between two components.
The requestCode helps you to identify from which Intent you came back. For example, imagine your Activity A (Main Activity) could call Activity B (Camera Request), Activity C (Audio Recording), Activity D (Select a Contact).
onActivityResult , startActivityForResult , requestPermissions , and onRequestPermissionsResult are deprecated on androidx.
onActivityResult - resultCode is always 0.
You are calling startActivityForResult()
from your Fragment
. When you do this, the requestCode
is changed by the Activity
that owns the Fragment
.
If you want to get the correct resultCode
in your activity try this:
Change:
startActivityForResult(intent, 1);
To:
getActivity().startActivityForResult(intent, 1);
The request code is not wrong. When using v4 support library fragments, fragment index is encoded in the top 16 bits of the request code and your request code is in the bottom 16 bits. The fragment index is later used to find the correct fragment to deliver the result.
Hence for Activities started form fragment object, handle onActivityResult requestCode like below:
originalRequestCode = changedRequestCode - (indexOfFragment << 16) 6 = 196614 - (3 << 16)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With