Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IllegalStateException: <MyFragment> is not currently in the FragmentManager

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.

like image 283
marmor Avatar asked Aug 13 '12 15:08

marmor


1 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:

    @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();         }     } 
like image 92
Greg Ennis Avatar answered Sep 22 '22 20:09

Greg Ennis