This is a famous problem of getting result from activity to a nested fragment, the activity could send the result to only the Fragment that has been attached directly to Activity but not the nested one. That's the reason why onActivityResult of nested fragment would never been called no matter what. In my case i have one activity that contains one fragment which has a viewPager with bunch of fragments. In one of this fragments of the viewPager i try to start a camera intent, the result returned by this intent is never sent to the last fragment, i tried severals answers that i found but none of them is robust, one of the solutions was to create an EventBus object to diffuse the resultCode from activity to all the fragments but it doesn't work for this case, any help??
1 Answers
I might have a working solution for you since I used to be in a very similar situation.
In short terms I stopped relying on Fragment
's onActivityResult()
and implemented a working logic myself.
The only onActivityResult()
you should trust is the one of your Activity
.
You may create an interface
like this one
public interface ActivityResultDispatcher {
// Pass anything you want, Bundle, Intent, ecc...
// For the sake of simplicity I'm using Bundle...
public void dispatchResultData(final Bundle data);
}
and have your Fragment
classes implement it.
The communication between your Activity
and your primary Fragment
should be very easy that you can do something like this (in your Activity
):
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
final Bundle bundle = new Bundle();
// put data inside Bundle
this.primaryFrament.dispatchResultData(bundle);
}
Now, your primary Fragment
is the one that holds the ViewPager
with the other Frament
classes.
So in your primary Fragment
you will do:
@Override public void dispatchResultData(final Bundle data) {
for (int i = 0; i < MyViewPager.NUM_FRAGMENTS; i++) {
final ActivityResultDispatcher subFragment = (ActivityResultDispatcher) this.retrieveFragment(i);
// some fragments in ViewPager may be dynamically deleted
if (subFragment != null) {
subFragment.dispatchResultData(data);
}
}
}
The function retrieveFragment(final int position)
is a very cozy piece of code I had found on the web.
An implementation for a ViewPager
works like this:
public Fragment retrieveFragment(final int position) {
return this.fragmentManager.findFragmentByTag("android:switcher:" + R.id.my_pager_id + ":" + position);
}
All your active Fragment
classes in the ViewPager
will receive the Bundle
and you can decide what to do with it.
You may pass more information to the dispatcher, such as
public void dispatchResultData(final Bundle data, final int requestCode);
and have your Fragment
decide if it should answer to the function call.
You have basically built a complete fully-working onActivityResult()
utility and can be sure that all of your Fragments
(if instantiated) will receive the result.

- 3,724
- 1
- 17
- 45