-1

So I have this wonderful function:

public static MenuPictureFragment newMenuPictureFragment(FragmentActivity fragmentActivity, String userIdParam, int containerId){
    MenuPictureFragment menuPictureFragment = (MenuPictureFragment) fragmentActivity.getSupportFragmentManager().findFragmentByTag(fragmentActivity.getString(R.string.fragment_tag_menu_picture_fragment));

    try {
        if(menuPictureFragment == null) {
            menuPictureFragment = MenuPictureFragment.newInstance(userIdParam);
        } 
        FragmentTransaction fragmentTransaction = fragmentActivity.getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(containerId, menuPictureFragment, fragmentActivity.getString(R.string.fragment_tag_menu_picture_fragment));
        fragmentTransaction.commit();
    } catch (RuntimeException re){
        //intentionelly empty
    }

    return menuPictureFragment;
}

menuPictureFragmentis a fragment inside a fragement, if I navigate away from the parent fragment, at some point the app crashes with a IllegalStateException: Fragment already addedmessage.

Shouldn't that Exception been caught? Adding !menuPictureFragment.isAdded() doesn't help either.

If I replace fragmentTransaction.add with fragmentTransaction.replace the exception disappears, but the menuPictureFragment is only present in the beginning, after circling back (when before the Exception was thrown) the fragment is not shown anymore.

What the hell is going on here?

murkr
  • 634
  • 5
  • 27

2 Answers2

1

Solution was: you need to use getChildFragmentManager() instead of getSupportFragmentManager() if it's a nested fragment / if you add the fragment to a fragment.

murkr
  • 634
  • 5
  • 27
0

the actual problem most likely is:

that tag R.string.fragment_tag_menu_picture_fragment might not have been applied -

and so it will always return null (which can be understood as "fragment tag not found").

and then it subsequently will attempt to add that MenuPictureFragment twice -

which will throw that uncaught IllegalStateException. For example:

String tag = fragmentActivity.getString(R.string.fragment_tag_menu_picture_fragment);
menuPictureFragment = MenuPictureFragment.newInstance(userIdParam);
menuPictureFragment.setTag(tag);

or pass the desired String tag into some method .newInstance(String userId, String tag) and let the Fragment set it's own tag.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
  • I already checked that, `fragmentActivity.getSupportFragmentManager().findFragmentByTag(fragmentActivity.getString(R.string.fragment_tag_menu_picture_fragment));` return the right value. – murkr Jun 11 '19 at 10:26
  • also setTag doesnt exist – murkr Jun 11 '19 at 11:27