IllegalStateException: <MyFragment> is not currently in the FragmentManager

marmor picture marmor · Aug 13, 2012 · Viewed 22.3k times · Source

I know it sounds like a duplicate of FragmentStatePagerAdapter IllegalStateException: <MyFragment> is not currently in the FragmentManager but his solution isn't relevant to my case.

I'm getting the following crash very rarely:

java.lang.RuntimeException: Unable to pause activity {MyActivity}:

...

Caused by: java.lang.IllegalStateException: Fragment MyFragment {40648258 id=0x7f070051} is not currently in the FragmentManager at android.support.v4.app.FragmentManagerImpl.putFragment(MT:516) at android.support.v4.app.FragmentStatePagerAdapter.saveState(MT:185) at android.support.v4.view.ViewPager.onSaveInstanceState(MT:881)

...

at android.view.View.saveHierarchyState(View.java:6238) at com.android.internal.policy.impl.PhoneWindow.saveHierarchyState(PhoneWindow.java:1522) at android.app.Activity.onSaveInstanceState(Activity.java:1138) at android.support.v4.app.FragmentActivity.onSaveInstanceState(MT:480) at MyActivity.onSaveInstanceState(MT:336)

It seems like this is the weird code I can't understand from FragmentStatePagerAdapter:

for (int i=0; i<mFragments.size(); i++) {
    Fragment f = mFragments.get(i);
    if (f != null) {
        if (state == null) {
            state = new Bundle();
        }
        String key = "f" + i;
        mFragmentManager.putFragment(state, key, f);
    }
}

It looks like the adapter gets my Fragment from mFragments but can't add its state to FragmentManager.

I've couldn't find any way to recreate this on my test devices, only received this from some users.

I'm using support package v4.

Any help? Thanks.

Answer

Greg Ennis picture Greg Ennis · Apr 16, 2015

The FragmentStatePagerAdapter is a horrible piece of code riddled with bugs acknowledge or not by Google and so I use this code to fix this particular crash:

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // Yet another bug in FragmentStatePagerAdapter that destroyItem is called on fragment that hasnt been added. Need to catch
        try {
            super.destroyItem(container, position, object);
        } catch (IllegalStateException ex) {
            ex.printStackTrace();
        }
    }