To avoid Activity state loss, need to be sure that we do not commit fragment transactions after activity's onSaveInstanceState
called. -which gets called after onStop
-
You can check detail from the link below:
http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html
As you can see from below:
https://developer.android.com/reference/android/app/Activity.html#onRestoreInstanceState(android.os.Bundle)
Activity's onRestoreInstanceState
is called after onStart
method. I think (by the way, i'm not sure which tutorial you are talking about, i'm just thinking loudly) when saying "In the Android Fragments Tutorial it clearly states that "Once the activity reaches the resumed state, you can freely add and remove fragments to the activity." you can be sure that activity's state is restored. So you can add / remove your fragments but adding or removing fragments in onResume can cause some other issues.
What i suggest is simply check if savedInstanceState
null and than do your operations in activity's onCreate
method. With this approach we check if there's a previous state to be restored. Do not commit fragment transactions after onStop
called which can cause IllegalStateException
(For example in result of long running background tasks such as async tasks.)
Here you can see an official example from here:
https://developer.android.com/training/basics/fragments/fragment-ui.html