How to fix “Can not perform this action after onSaveInstanceState” on Android Fragments

Published by Igor Khrupin on

Recent I’ve this bug on my project.
This bug comes when app awake from sleep.
I’ve spent a lot of time to fix it. And finally I got the solution.

My project is Activity with Fragments.
The error text is:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3113)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3062)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3035)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1268)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4945)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1327)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1338)
at android.support.v4.app.FragmentManagerImpl.popBackStack(FragmentManager.java:501)
at android.support.v4.app.DialogFragment.dismissInternal(DialogFragment.java:180)
at android.support.v4.app.DialogFragment.dismiss(DialogFragment.java:155)
at

To fix it you need save instance of your Fragments. To do this you need just override onSaveInstanceState method for your Fragment.

@Override
public void onSaveInstanceState(Bundle outState) {
	super.onSaveInstanceState(outState);
	outState.putString(BundleKeys.MESSAGE, message);
}

Also you need restore fragment state in onCreateView of onActivityCreated methods

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	if (savedInstanceState != null) {
			if (!savedInstanceState.isEmpty()) {
			Loger.i(TAG, "!savedInstanceState.isEmpty()");
			if (message == null) {
				message = new Gson().fromJson(savedInstanceState.getString(BundleKeys.MESSAGE), Message.class);
			}
		}
	}
}

Hope it help you.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.