IllegalStateException: <MyFragment> is not currently in the FragmentManager IllegalStateException: <MyFragment> is not currently in the FragmentManager android android

IllegalStateException: <MyFragment> is not currently in the FragmentManager


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();        }    }


This can happen when a FragmentStatePagerAdapter is set on a ViewPager, with the Fragments being populated, but not yet added to the FragmentManager due to the Activity pausing before layout has occurred for the ViewPager. This is reliably hit by starting another Activity from onCreate, with the Adapter also set in onCreate. In that situation, it's best to hold off on setting the Adapter, and set it onActivityResult instead. See this issue: https://code.google.com/p/android/issues/detail?id=77285

I've also submitted a patch to check for the Fragment having been added before trying to save state.


Use getChildFragmentManager() instead of getFragmentManager() if you have fragments hierarchy. eg. if you have fragments pager.