Wrong requestCode in onActivityResult

半腔热情 提交于 2019-11-26 23:24:29
Changwei Yao

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);
Ashlesha Sharma

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)

Easier:

int unmaskedRequestCode = requestCode & 0x0000ffff

Check for the lower 16 bits, just unmask it doing a logical AND with the upper 16 bits zeroed

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    final int unmaskedRequestCode = requestCode & 0x0000ffff

    if(unmaskedRequestCode == ORIGINAL_REQUEST_CODE){
      //Do stuff

    }
}
Nilesh Tiwari

If you are providing constant make it public and then use in startActivityResult

example:

public static final int REQUEST_CODE =1;
getActivity().startActivityForresult(intent, REQUEST_CODE);

You can also define
super.onActivityResult(requestCode, resultCode, data)
in Activity (if you overrideonActivityResult) at this

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {

        ...

        default:
            super.onActivityResult(requestCode, resultCode, data);
    }
}

and call startActivityForResult(intent, requestCode) inside your Fragment

in Fragment

  getActivity().startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);

in Main Activity:

if (requestCode == PLACE_PICKER_REQUEST) {
            if (resultCode == RESULT_OK) {    
     //what ever you want to do
            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!