androidandroid-fragmentschild-fragment

Getting IllegalStateException with removing a child fragment


I am using child fragments. Fragment A adds a child fragment B:

B fragment = new B(); // B is a child
getChildFragmentManager().beginTransaction().add(fragment, null).commit();

Then later B removes itself with the following:

// in the B's code:
getChildFragmentManager().beginTransaction().remove(this).commit();

But I am getting the exception:

java.lang.IllegalStateException: Recursive entry to executePendingTransactions
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1473)
            at android.support.v4.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:1965)
            at android.support.v4.app.Fragment.performDestroy(Fragment.java:2006)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
            at android.support.v4.app.FragmentManagerImpl.removeFragment(FragmentManager.java:1235)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:710)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Solution

  • Within the child fragment we need to use FragmentManager from the parent fragment:

    getParentFragment().getChildFragmentManager().beginTransaction().remove(this).commit();
    

    So, the getParentFragment() was the missing part.