Search code examples
androidandroid-fragmentsillegalstateexception

IllegalStateException: Fragment already added not caught with try-catch


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?


Solution

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