Search code examples
androidnullresumerecycle

How to handle data missing after resume


I got some issue when I developing an App.

After I minimized the app or turn the screen off, and open lot of other apps or reopen the phone after a long time. When I restart my app, it try to resume and keep showing the same page(with fragment). But the data I need was already been destroyed so it will be null. The data is an object array, I know maybe I can store them in db. But due to the data will update every time user click something. So I don't want to save it into data base, I guess that means lot of storage I/O witch is not necessary. I'm wondering if there is any solution to restart the hole app when things is destroyed? Or the only way to make it happen is I handle the null array and do the reload myself? I don't really want to do that cause I guess that will bring me many unexpected issues cause the data is related with many pages. Too many situations I have to consider when do switching pages.

Are there any advice?


Solution

  • But the data I need was already been destroyed so it will be null

    That is because your process was terminated and you did not save your state.

    But due to the data will update every time user click something

    Or, you could fork a thread to save the data as part of your onPause() or onStop() methods. There are many possibilities between "never save" and "save on every click".

    So I don't want to save it into data base, I guess that means lot of storage I/O witch is not necessary

    If you want the data to be there 30+ minutes after the user left the app, your choices are to save the data locally (file, database, SharedPreferences) or save the data on the Internet somewhere.

    For small amounts of data over shorter time periods, you could put the data in the Bundle supplied to onSaveInstanceState() and then pull the data out of the Bundle again later (e.g., in onRestoreInstanceState() of your activity). You already should be doing this to handle screen rotations and other configuration changes.

    I'm wondering if there is any solution to restart the hole app when things is destroyed?

    You are welcome to add android:clearTaskOnLaunch="true" to your launcher activity, to indicate that you always want to start over from scratch whenever the user leaves your app and tries to come back to it. Users will not appreciate this, as this means that they will lose their state even for being out of your app briefly (e.g., a quick reply to a text message). This attribute does not terminate your process, but it will force the user back to the launcher activity and will eliminate any other activities that had been in your app previously.

    Or the only way to make it happen is I handle the null array and do the reload myself?

    That is what developers normally do, yes.