To reproduce, get the SSCCE Android Project on Github and :
Touch the hamburger to display navigation menu
Select Employees
Select an Employee
Touch the back button
Touch the Overview button
Select the application from the list
Touch the hamburger to display navigation menu
Select Employees
Select an Employee => IllegalStateException
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1538) at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1556) at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:696) at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:662) at example.com.replacefragments_onitemclick.fragments.FragmentChange.onFragmentChange(FragmentChange.java:88)
fragmentTransaction.commit(); // IllegalStateException: FragmentChange.java:88
The reason for the exception is clear: With the replace statement, it is trying to replace a fragment that is attached to a now non-existent Activity instance.
Overriding onSaveInstanceState()
as suggested here has no effect.
Numerous questions suggest using commitAllowingStateLoss()
. It does not fix the problem and apparently is kind of a hack anyway.
Also, there are answers that say to keep a reference to the old Activity. This does not seem right.
How can I prevent this exception?