onRestoreInstance State Null in Fragment

50 Views Asked by At

I have an app with several fragments and a Main Activity. My fragments are set up to display content in a Frame Layout inside of Main Activity. Kind of like a view pager.

Each fragment consists of a list view. I store my the lists' contents in Main Activity.

When the app is paused, (When the user presses the device home button) I need to save the app's values in a bundle. For some reason, onRestoreInstanceState() is never being called when the user resumes the application. As a result I don't get the values for my variables.

Sometimes the app crashes when the user attempts to resume from a separate application. This only happens when either the app has been in the background for a long period of time, or when the device gets low on memory.

Should I be using onRestoreInstanceState() or something different? Is it possible to override onRestoreInstanceState() and and call it manually?

1

There are 1 best solutions below

0
On

Usually what happens is that in such cases, android just kills of the entire app process.

Android then goes to recreate your stack and all the fragments. It's also clever when doing so because it will pass the saved bundle inside both your

onCreate and onCreateView

You can check these bundles for nullity and use them like you would use a normal bundle and restore your data from it. I generally save a large list inside sqlite and just save a boolean flag to indicate if state was saved inside the bundle.

There's a 1mb limit on the bundle saved and this is for an entire application. In newer versions, api 24+ i think, you get an exception if state saved is bigger than that. Earlier there was just a logged warning inside logcat