Problem:
I add a fragment to a LinearLayout, programmatically. It shows up in my activity, great. I turn the device —> configuration changes: everything is destroyed to be recreated. But, before onDestroy() is called, onSaveInstanceState() should be called. It is the case for the parent activity, but not for the fragment I've added. Why ?
Code:
The XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id/parent_LL"
android:stuff="myStuff"
>
<LinearLayout
android:id="@id/categories_activity_LL1"
android:stuff="myStuff" />
<LinearLayout
android:id="@id/categories_activity_LL2"
android:stuff="myStuff" />
</LinearLayout>
I add the fragment to the UI in the parent activity:
ft.add(container1, categories, CatFragIds.CATEGORIES.toString()).commit();
I override the onSaveInstanceState() of my fragment:
@Override
public void onSaveInstanceState(Bundle outState) {
// Récupère extensible
boolean extensible = ((CategoryAppsListView) this.getListView())
.isExtensible();
mState.setExtensible(extensible);
// Transmet l'état de CategoriesListElems
FragmentManager fm = getFragmentManager();
@SuppressWarnings("unchecked")
FragRetainObject<CategoriesListElemsState> retainedState =
(FragRetainObject<CategoriesListElemsState>)
fm.findFragmentByTag(CATEGORIESLISTELEMS_STATE+"_"+this.getTag());
if( retainedState == null) {
retainedState =
FragRetainObject.<CategoriesListElemsState>newInstance(mState);
fm.beginTransaction()
.add(retainedState, CATEGORIESLISTELEMS_STATE+"_"+this.getTag()).commit();
}
else retainedState.setRetainObj(mState);
super.onSaveInstanceState(outState);
}
Thank you for your time!! :-)
In the normal scenario, there is no need to recreate the activity and neither are called. Note that onSaveInstanceState() is called when your activity goes into the background and NOT when the app process is about to be killed.
The method onSaveInstanceState() isn't called when an Activity finishes naturally like on a back button press. That's your app itself destroying the Activity . The method is only called if the Android OS anticipates that it may have to kill your activity to reclaim resources.
onSaveInstanceState() is a method used to store data before pausing the activity.
The onSaveInstanceState() method allows you to add key/value pairs to the outState of the app. Then the onRestoreInstanceState() method will allow you to retrieve the value and set it back to the variable from which it was originally collected.
I had the same problem. There are two possible answers:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With