Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong requestCode in onActivityResult

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?

like image 816
Dimanoid Avatar asked May 12 '12 14:05

Dimanoid


People also ask

What can I use instead of Startactivity for results?

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.

What is requestCode in startActivityForResult?

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).

Can startActivityForResult still be used?

onActivityResult , startActivityForResult , requestPermissions , and onRequestPermissionsResult are deprecated on androidx.

What is result code in onActivityResult?

onActivityResult - resultCode is always 0.


2 Answers

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); 
like image 174
Changwei Yao Avatar answered Oct 04 '22 15:10

Changwei Yao


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) 
like image 42
Ashlesha Sharma Avatar answered Oct 04 '22 13:10

Ashlesha Sharma