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

nirvik picture nirvik · Aug 29, 2013 · Viewed 12.3k times · Source

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

Answer

esentsov picture esentsov · Aug 29, 2013

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