android – Wrong requestCode returned onActivityResult from another Activity-ThrowExceptions

Exception or error:

I have an Activity that calls another Activity, that calls some other Activities.
I send to the last Activity to get a result, and then i send back the result to the fist Activity.

The flow is somthing like

A -> B -> C -> D -> C -> B -> A

With the flow from A to D is made of startActivityForResult and the flow from D to A is made of onActivityResult.

From D to B the requestCode is always the same (the one I decided), but from B to A it suddenly change from my value to a random value (in this particular case 196614).

This is the code I use to call the activity B from activity A:

filterByCatalogue.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), CatalogueContainerActivity.class);
            startActivityForResult(intent, Defines.FILTER_BY_CATALOGUE);
        }
    });

(With filterByCatalogue as a FrameLayout)

This is the code I use to call back the activity A:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Defines.FILTER_BY_CATALOGUE) {
            if (resultCode == RESULT_OK) {
                Intent intent = new Intent();
                intent.putExtra("article", data.getStringExtra("article"));
                setResult(RESULT_OK, intent);
                finish();
            }
        }
    }

I’ve searched a lot but I can’t find where I go wrong….

How to solve:

Just replace

startActivityForResult(intent, Defines.FILTER_BY_CATALOGUE);

with

getActivity().startActivityForResult(intent, Defines.FILTER_BY_CATALOGUE);

It will work for sure. 🙂

###

The request code is not random. 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 to. Reference.

For example, 196614 is really 3 << 16 + 6 where 3 is the fragment index plus one and 6 is your request code.

Morale: Don’t mix activity/fragment startActivityForResult() and onActivityResult(). When started from an activity, process the result in the activity. When started from a fragment, process the result in the fragment.

Leave a Reply

Your email address will not be published. Required fields are marked *