I’ve faced this problem sometimes but I’ve never written about it. It’s very interesting because it proves that the Android avoid at all costs lose the state of the activity. This error commonly happens when you try to commit a fragment transaction after the onSaveInstanceState() be called, in other words, when you do it in onPause() or onStop(), depending of the OS version (read here to understand). After the onSaveInstanceState() any new state won’t be saved even the new fragment transaction and the Android doesn’t allow it, throwing an
So, if this exception is happening, take a look in what you are doing after onSaveInstanceState()!
- Don’t commit a fragment transaction inside the onResume(). If you use Android support library, onResume method isn’t the right place, where to play with fragments. (see Documentation). There are some cases in which this method can be called before the activity’s state has been restored. Do it on onCreate() or onResumeFragments() (the fragment-orientated version of onResume()).
- Don’t commit a fragment transaction inside AsyncTasks or Worker Threads, because it’s detached of the life cycle, and the state cannot be saved.
- Prefer commit fragment transactions inside onCreate().
- Be sure you are commiting the transaction before the onSaveInstanceState()