Android onActivityResult not called from fragment

Today I had an issue with onActivityResult() method which was not called inside a fragment. My first impulse was to move the method inside the activity that hosts the fragment, and that’s what I actually did. So, I ran my app in debug mode and when I saw that the breakpoint stopped in the onActivityResult method from the activity I said, OK, at least it works here. But then, I noticed that the requestCode (the int value you need to use when calling startActivityForResult()) had a very strange value: requestCode=132897 I spent some time debugging the code thinking that maybe I used a wrong constant.

But that was not the case. It seems that fragments override somehow the requestCode. So the solution was to do this:

In Activity (the one that hosts the fragment):

  • override the onActivityResult() method and call super.onActivityResult. Calling super is mandatory! It won’t work otherwise. So this is the magic solution, to override and call super for onActivityResult method inside the hosting activity of your fragment.
  @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Override this method in the activity that hosts the Fragment and call super
        // in order to receive the result inside onActivityResult from the fragment.
        super.onActivityResult(requestCode, resultCode, data);
    }

In Fragment

  • override onActivityResult() and let your logic here (if this is what you wanted)
  • when starting the activity use just startActivityForResult() and not getActivity.startActivityForResult()

Note: If your activity extends another activity make sure that the parent activity does not overrides your onActivityResult().

Now, if you add a breakpoint in your fragment on this method, you will see that now is called without any other problems 🙂 I hope this post helped you 😉

 

Menu