Home » Android » java – IllegalStateException: <MyFragment> is not currently in the FragmentManager

java – IllegalStateException: <MyFragment> is not currently in the FragmentManager

Posted by: admin April 23, 2020 Leave a comment


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

at android.view.View.saveHierarchyState(View.java:6238) at
at android.app.Activity.onSaveInstanceState(Activity.java:1138) at
android.support.v4.app.FragmentActivity.onSaveInstanceState(MT:480) at

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?

How to&Answers:

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:

    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) {


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.


I’ve encountered the exact exception.

In my case, I have several fragments managed by FragmentPagerStateAdapter, but sometimes the fragment will get switched in position.

I override getItemPosition() and return the new position and call notifyDataSetChanged() to refresh ViewPager. Everything works fine but sometimes when I leave the ViewPager the crash occurs.

After several hours digging into it, I found there’s a bug in FragmentPagerStateAdapter.

The adapter not only caches states, but also caches the fragments that it consider ‘active’

private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<Fragment.SavedState>();
private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();

But it does not check if the fragments’ position has invalidated or moved.

That’s how it get this exception:

1.I have A,B,C three Fragments in ViewPager and Adapter.

2.I switched the position to B,A,C in adapter and called notifyDataSetChanged().

3.ViewPager re-layout the fragment by new order. But the mFragments cache is still {A,B,C}

4.Swipe few pages, ViewPager will ask adapter to destroy the first Fragment. then the fragment B, instead of A, is set to null in the cache. Now the mFragments is {null,A,C}.

5.Leave the ViewPager, and onSaveInstanceState is triggered. all fragments in mFragments is considered active and putFragment() is called until FragmentManagerImpl found A not in it and throw a Exception.

So here’s my not so gentle solution:

1.Copy the entire FragmentPagerStateAdapter source code.

2.Override the notifyDataSetChanged() method to rearrange the caches as below.

public void notifyDataSetChanged() {
  List<Fragment> oldFragments = new ArrayList<>(mFragments);
  List<Fragment.SavedState> oldStates = new ArrayList<>(mSavedState);
  for (int i = 0; i < getCount(); i++) {
    if (i < mFragments.size()) {
      Fragment f = mFragments.get(i);
      if (f != null) {
        int newPosition = getItemPosition(f);
        if (newPosition == POSITION_UNCHANGED || newPosition == i) {
        } else if (newPosition == POSITION_NONE) {
          if (i < mSavedState.size()) {
            mSavedState.set(i, null);
          mFragments.set(i, null);
        } else {
          while (i >= mFragments.size()) {
          if (oldStates.size() > i) {
            mSavedState.set(newPosition, oldStates.get(i));
          mFragments.set(newPosition, oldFragments.get(i));
      } else {
         * No Fragment but that's possible there's savedState and position has
         * changed.

Hope that works for some of you!


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

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


Use the following

final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(f, key);

instead of

mFragmentManager.putFragment(state, key, f);

and pass the bundle explicitly..

For reference,



Are you calling FragmentStatePagerAdapter.instantiateItem() from your own code? Generally, the ViewPager should be the only client that calls this method, however, it’s easy to come across workarounds for other limitations that rely on this method.

Due to the way FragmentStatePagerAdapter works, I would guess that the adapter has instantiated the Fragment, added it to it’s internal collection of Fragments, and even began a transaction to add that Fragment to the FragmentManager, but that fragment transaction has not been committed or executed. This is exactly what instantiateItem() does when it hasn’t already instantiated the requested Fragment.

Another method, FragmentStatePagerAdapter.finishUpdate() is responsible for committing the transaction as well as for executing the pending transactions. finishUpdate() must be called after instantiateItem() or else the Fragment may not be added to the FragmentManager.

Try something like this:

// Get the current Fragment presented by the ViewPager.
Fragment fragment = pagerAdapter.instantiateItem(viewPager, viewPager.getCurrentItem());
return fragment;

startUpdate() has an empty implementation as of API level 19.


Write in Activity onCreate() method :

pager = (ViewPager) findViewById(R.id.pager);
    adapter = new SwipePagerAdapter(getSupportFragmentManager());
    pageOneFragment = new PageOneFragment();

Adapter code:

public class SwipePagerAdapter extends FragmentStatePagerAdapter
private final ArrayList<Fragment> mFragments = new ArrayList<Fragment>();

public SwipePagerAdapter(FragmentManager fm)

public Fragment getItem(int position)
    return mFragments.get(position);

public int getCount()
    return mFragments.size();

public void addFragment(Fragment fragment)

public void destroyItem(ViewGroup container, int position, Object object)
    super.destroyItem(container, position, object);

public CharSequence getPageTitle(int position)
    return super.getPageTitle(position);


You could try using mFragmentManager.add();


Try using

use fragmentTransaction.add()


Fragments in the ViewPager are fixed, instead of trying to replace the fragments in the adapter, try to give a different set of fragments and notifyDataSet changed, or take the advantage of FrameLayout to show another fragment over the view pager tab’s current fragment.

There is my solution that works:

Swipe Gesture applied at Fragment level along with ViewPager with it's default swipe disabled


Double-check whether you’ve implemented onSaveInstanceState and onRestoreInstanceState in your activity, and verify that they’re correctly saving and loading the state of your fragments.