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

Ixx picture Ixx · Jul 2, 2012 · Viewed 19.2k times · Source

I'm getting this on some cases, in onResume(), of an activity which uses a FragmentStatePagerAdapter. When using device's back button. Not always. Not reproducible.

I'm using support package v4, last revision (8).

Already searched with google, no success finding a useful answer.

Looking in the source, it's thrown here: FragmentManager.java

@Override
public void putFragment(Bundle bundle, String key, Fragment fragment) {
    if (fragment.mIndex < 0) {
        throw new IllegalStateException("Fragment " + fragment
                + " is not currently in the FragmentManager");
    }
    bundle.putInt(key, fragment.mIndex);
}

But why is the index of fragment < 0 there?

The code instantiating the fragments:

@Override
public Fragment getItem(int position) {
    Fragment fragment = null;

    switch(position) {
        case 0:
            fragment = MyFragment.newInstance(param1);
            break;
        case 1:
            fragment = MyFragment2.newInstance(param2, param3);
            break;
    }
    return fragment;
}

@Override
public int getCount() {
    return 2;
}

Answer

Thomas G. picture Thomas G. · Feb 3, 2014

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

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