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

If your ViewPager is layouted inside a fragment (not an activty) :

mViewPager.setAdapter(new MyFragmentStatePagerAdapter(getChildFragmentManager()));


I had the same error here, but for another reason.

In my case I had override getItemPosition in my FragmentStatePagerAdapter. My ideia was to return the position, if the item exists, or a POSITION_NONE, if it doesn't exists anymore.

Well, my problem was the fact that when my collection got empty I returned POSITION_NONE. And that broke everything.

My fix was to return POSITION_UNCHANGED when I had an empty collection.

Hope it helps someone else.


The two key things to understand the bug are:

  1. It happens sometimes.
  2. It happens in onResume().

Given this information, it's likely that the ViewPager is not retaining the state of your Fragments. If you are manipulating the Fragments directly from the Activity, it could be the case that the off-page Fragment is getting destroyed and your Activity is trying to manipulate a null fragment. To retain the Fragment's state even when it is not in the current screen, the fix is pretty simple:

private static final int NUM_ITEMS = 2;

ViewPager mPager = /** instantiate viewpager **/;
mPager.setOffscreenPageLimit(NUM_ITEMS-1);

You can read about it here:

ViewPager Fragments getting destroyed over time?