Android : I always have savedInstanceState == null
when I relaunch my app.
I have a fragment where I want to store / reuse data after stopping the application.
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mPrefs = android.preference.PreferenceManager.getDefaultSharedPreferences(getActivity());
if (savedInstanceState != null) {
mLoading = savedInstanceState.getBoolean(OUTSTATE_LOADING, false);
mCurrentFiliere = savedInstanceState.getInt(OUTSTATE_CURRENT_FILIERE, 0);
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(OUTSTATE_CURRENT_FILIERE, mCurrentFiliere);
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState != null) {
mCurrentFiliere = savedInstanceState.getInt(OUTSTATE_CURRENT_FILIERE);
}
}
Both methods onCreate
and onViewStateRestored
return null
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="@android:id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:indeterminate="true"
android:visibility="gone" />
</FrameLayout>
And I haven't found any answer in other posts...
Well, due to a lack of comprehension of me of the saves on Android, my question isn't very good because my code works fine!
Indeed if I don't close my application, I don't lose any data.
My issue was how to conserve data when I close my application and the answer is to use preferences
. And this way i can close my application and relaunch it without losing the saved data.
It's obvious when we know the correct way to save....
My mistake was (very simply): savedInstanceState save between onCreate
and onStop
and preferences
save when you are on onDestroy