"Can not perform this action after onSaveInstanceState" - why am I getting this exception from my activity's onResume method? "Can not perform this action after onSaveInstanceState" - why am I getting this exception from my activity's onResume method? android android

"Can not perform this action after onSaveInstanceState" - why am I getting this exception from my activity's onResume method?


I think I know the answer - I'm using the FragmentActivity from v4 compatibility library, and so I need to perform my fragment transactions in onResumeFragments instead of in onResume. Can someone confirm?


you can use the method commitAllowingStateLoss()

but be aware you can lose the state of your activityas you can see in google's android referencewhich explain the different between the two in the following way

Like commit() but allows the commit to be executed after an activity's state is saved. This is dangerous because the commit can be lost if the activity needs to later be restored from its state, so this should only be used for cases where it is okay for the UI state to change unexpectedly on the user.

from my experience it may cause the addToBackStack method not to work sometimes so you will need to add it manually on the fragment and of course the state won't be saved (textbox text ext.)


this worked for me... found this out on my own... hope it helps you!

1) do NOT have a global "static" FragmentManager / FragmentTransaction.

2) onCreate, ALWAYS initialize the FragmentManager again!

sample below :-

public abstract class FragmentController extends AnotherActivity{protected FragmentManager fragmentManager;protected FragmentTransaction fragmentTransaction;protected Bundle mSavedInstanceState;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    mSavedInstanceState = savedInstanceState;    setDefaultFragments();}protected void setDefaultFragments() {    fragmentManager = getSupportFragmentManager();    //check if on orientation change.. do not re-add fragments!    if(mSavedInstanceState == null) {        //instantiate the fragment manager        fragmentTransaction = fragmentManager.beginTransaction();        //the navigation fragments        NavigationFragment navFrag = new NavigationFragment();        ToolbarFragment toolFrag = new ToolbarFragment();        fragmentTransaction.add(R.id.NavLayout, navFrag, "NavFrag");        fragmentTransaction.add(R.id.ToolbarLayout, toolFrag, "ToolFrag");        fragmentTransaction.commitAllowingStateLoss();        //add own fragment to the nav (abstract method)        setOwnFragment();    }}