I have a parent Fragment Activity that has a ViewPager which contains a child ViewPager. The child ViewPager contains Fragments for each page. I communicate between these ch
I had this problem with nested fragments and none of the stackoverflow solutions worked for me. Just it seems, that there is a bug with support library, when dismissed fragments still store pointers to previous activity (so getFragmentManager() just returns null, because it is called on already destroyed activity), that's why you need to manage pointers yourself. I ended up with a following solution:
1. In the first level fragment I was saving pointer to the activity in the method
public void onAttach(Activity activity) {
super.onAttach(activity);
parentActivity = activity; // parentActivity is static variable
}
2. In the activity which handles fragments I ended up with this code:
private void launchFragment(Fragment fragment, Activity parent) {
FragmentTransaction transaction;
if(parent == null)
transaction = mFragmentManager.beginTransaction();
else // for nested child fragments, workaround for Android parent pointer bug
transaction = parent.getFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
You should pass parentActivity of FIRST level fragment only when you are calling SECOND level (nested) fragments, as it seems that this bug is only with nested ones after you bring your app from foreground.