Wrong requestCode returned onActivityResult from another Activity

ぐ巨炮叔叔 提交于 2020-01-01 07:30:06

问题


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


回答1:


Just replace

startActivityForResult(intent, Defines.FILTER_BY_CATALOGUE);

with

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

It will work for sure. :)




回答2:


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.



来源:https://stackoverflow.com/questions/27225038/wrong-requestcode-returned-onactivityresult-from-another-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!