Programming

getting exception IllegalStateException Can not perform this action after onSaveInstanceState

25 September 2026 · 6 min read

getting exception IllegalStateException Can not perform this action after onSaveInstanceState

Encountering the dreaded “IllegalStateException: Can not perform this action after onSaveInstanceState” in your Android development journey can be incredibly frustrating. This exception typically arises when you attempt to commit a FragmentTransaction after the activity’s state has been saved, often leading to app crashes and a disrupted user experience. Understanding the lifecycle of an Activity and Fragment, and how state saving plays a crucial role, is key to preventing this common error. In this comprehensive guide, we’ll delve into the intricacies of this exception, exploring its root causes, effective prevention strategies, and robust solutions to ensure a smooth and crash-free experience for your users.

Understanding the onSaveInstanceState() Mechanism

The onSaveInstanceState() method is a critical part of the Android activity lifecycle. It’s called by the system before an activity is temporarily destroyed, such as during a configuration change (screen rotation) or when the system needs to reclaim resources. This method allows the activity to save its current state, including the state of its fragments, into a Bundle object. This Bundle is then used to restore the activity’s state when it’s recreated.

The problem occurs when you attempt to commit a FragmentTransaction after onSaveInstanceState() has been called. At this point, the system has already taken a snapshot of the activity’s state, and any subsequent changes to the FragmentManager can lead to inconsistencies and ultimately, the IllegalStateException.

Android developer documentation explicitly warns against performing FragmentTransactions after onSaveInstanceState(): “This is because the state of the activity is already saved, so any changes you make will be lost if the activity needs to be restored.”

Common Scenarios Leading to the Exception

Several common scenarios can trigger this exception. One frequent culprit is performing asynchronous operations, like network requests, that complete after the activity has been paused or stopped. If the result of such an operation triggers a FragmentTransaction, it can lead to the error if the activity’s state has already been saved.

Another common cause is handling configuration changes improperly. When the screen rotates, for instance, the activity is destroyed and recreated. If you’re committing FragmentTransactions in response to configuration changes without properly accounting for the activity lifecycle, you’re likely to encounter the IllegalStateException.

Here are some specific examples:

  • Updating UI elements within a Fragment after the Activity’s state is saved.
  • Replacing Fragments based on data received from a background thread.
  • Committing FragmentTransactions in onStop() or onDestroy().

Effective Prevention Strategies

Preventing this exception involves carefully managing FragmentTransactions within the activity lifecycle. A common solution is to use isFinishing() within your Activity to check if the activity is in the process of being finished. If it is, avoid committing any FragmentTransactions.

Another effective approach is to commit transactions within onResumeFragments(). This method is called after onResume() and guarantees that the FragmentManager is available and ready to handle transactions. This is particularly useful when restoring the state of fragments after a configuration change.

For asynchronous operations, ensure you check the activity’s state before committing any FragmentTransactions based on the operation’s result. You can use isAdded() within your fragment to check if it’s currently attached to an activity.

Robust Solutions and Workarounds

If unavoidable situations arise, consider using commitAllowingStateLoss(). While this method allows you to commit transactions even after onSaveInstanceState(), it’s crucial to understand the potential implications. As the name suggests, using this method might result in state loss if the activity needs to be restored. Use it judiciously and only as a last resort.

Here’s an ordered list of recommended steps to resolve the issue:

  1. Analyze your code to identify the exact point where the FragmentTransaction is being committed.
  2. Check if the transaction occurs after onSaveInstanceState(). Utilize lifecycle methods like onPause() and onStop() for debugging.
  3. Implement the preventative measures discussed above, prioritizing isFinishing() and onResumeFragments().
  4. If necessary, consider using commitAllowingStateLoss() with caution, understanding the potential for state loss.

Consider leveraging a robust event bus system to decouple communication between components and avoid direct Fragment manipulation from background threads. This can help prevent scenarios where transactions are triggered at inappropriate times.

FAQ: Common Questions about IllegalStateException

Q: What is the primary cause of the “IllegalStateException: Can not perform this action after onSaveInstanceState”?

A: Attempting to commit FragmentTransactions after the activity’s state has been saved, usually through onSaveInstanceState(), is the primary cause. This often happens during asynchronous operations or mishandling configuration changes.

Q: How can I prevent this exception?

A: The most effective prevention strategies include using isFinishing() to check the activity’s state, committing transactions within onResumeFragments(), and carefully managing transactions triggered by asynchronous operations.

By understanding the lifecycle of Activities and Fragments and implementing these strategies, you can create more robust and stable Android applications, free from the frustration of the “IllegalStateException: Can not perform this action after onSaveInstanceState” exception. This proactive approach will lead to a significantly improved user experience and reduce development time spent on debugging crashes. Explore resources like the official Android documentation and Stack Overflow for further insights and community support. Remember to prioritize user experience by handling these scenarios gracefully and providing informative error messages when necessary. For more in-depth information on Android development best practices, check out Android Developers documentation on Fragment lifecycle, Stack Overflow for relevant questions and answers, and Vogella’s tutorial on Android Fragments.

Question & Answer :
I have a Live Android application, and from market i have received following stack trace and i have no idea why its happening as its not happening in application code but its getting caused by some or the other event from the application (assumption)

I am not using Fragments, still there is a reference of FragmentManager. If any body can throw some light on some hidden facts to avoid this type of issue:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1109) at android.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:399) at android.app.Activity.onBackPressed(Activity.java:2066) at android.app.Activity.onKeyDown(Activity.java:1962) at android.view.KeyEvent.dispatch(KeyEvent.java:2482) at android.app.Activity.dispatchKeyEvent(Activity.java:2274) at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1668) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1720) at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1258) at android.app.Activity.dispatchKeyEvent(Activity.java:2269) at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1668) at android.view.ViewRoot.deliverKeyEventPostIme(ViewRoot.java:2851) at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2824) at android.view.ViewRoot.handleMessage(ViewRoot.java:2011) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:132) at android.app.ActivityThread.main(ActivityThread.java:4025) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:491) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) at dalvik.system.NativeStart.main(Native Method) 

This is the most stupid bug I have encountered so far. I had a Fragment application working perfectly for API < 11, and Force Closing on API > 11.

I really couldn’t figure out what they changed inside the Activity lifecycle in the call to saveInstance, but I here is how I solved this :

@Override protected void onSaveInstanceState(Bundle outState) { //No call for super(). Bug on API Level > 11. } 

I just do not make the call to .super() and everything works great. I hope this will save you some time.

EDIT: after some more research, this is a known bug in the support package.

If you need to save the instance, and add something to your outState Bundle you can use the following :

@Override protected void onSaveInstanceState(Bundle outState) { outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE"); super.onSaveInstanceState(outState); } 

EDIT2: this may also occur if you are trying to perform a transaction after your Activity is gone in background. To avoid this you should use commitAllowingStateLoss()

EDIT3: The above solutions were fixing issues in the early support.v4 libraries from what I can remember. But if you still have issues with this you MUST also read @AlexLockwood ’s blog : Fragment Transactions & Activity State Loss

Summary from the blog post (but I strongly recommend you to read it) :

  • NEVER commit() transactions after onPause() on pre-Honeycomb, and onStop() on post-Honeycomb
  • Be careful when committing transactions inside Activity lifecycle methods. Use onCreate(), onResumeFragments() and onPostResume()
  • Avoid performing transactions inside asynchronous callback methods
  • Use commitAllowingStateLoss() only as a last resort