简体   繁体   中英

Fragments startActivityForResult always return resultCode 0 and intent null on callback onActivityResult

I searched all over and there are similar posts about it, but can't find a solution!

My situation is I have an Activity A that holds a fragment , and from that fragment I want to start a new Activity B that should return some values to the fragment .

On the fragment

startActivityForResult(mapIntent, ConstantsUtils.TOMAP_REQUEST_CODE);

On the Activity B, to return the data

Intent returnIntent = new Intent();
returnIntent.putExtra(SerializationConstants.isSearchSaved, mAbItemsShown.ordinal());
setResult (ConstantsUtils.SUCCESS_RETURN_CODE, returnIntent);
finish();

On the fragment

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

switch (requestCode) {

    case ConstantsUtils.TOMAP_REQUEST_CODE:

            if (resultCode == ConstantsUtils.SUCCESS_RETURN_CODE) {
              //do some stuff 
            }
    }
}

onActivityResult from the fragment is successfully called, with the right requestCode but resultCode is always 0 and intent is always null .

I have no other onActivityResult implementation under Activity A.

In fact, I also try starting the activity from the fragment with getActivity().startActivityForResult(mapIntent, ConstantsUtils.TOMAP_REQUEST_CODE); and implementing onActivityResult on Activity A but it happens the same, right requestCode but wrong resultCode and intent .

I'm using Sherlock Action Bar so my fragment is a SherlockListFragment so I'm using the support library (r18) .

Can you help me? Thanks

Result code 0 is RESULT_CANCELLED .

The resultCode will be RESULT_CANCELED if the activity explicitly returned that, didn't return any result, or crashed during its operation.

Also the common reason of getting this code is a launching an activity in a new task (check your intent and manifest for flags, which lead to the start of a new task).

Also if you have a parent activity, you should set result code of it instead of set result code of its child (try to getParent and if it is not null, than set result code of it).

I spent some time to find out the reason. My mistake was put super.onBackPressed() in the onBackPress() method.

I called finish() in the method. But I think super.onBackPressed() will call the finish() automatically so you will get resultCode 0 always. So just remove the super.onBackPressed() line in the onBackPressed() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM