views:

124

answers:

1

I am using a separate class with only static fields, to store current application data. It is partly populated from sharedpreferences on application startup. The rest is data like results of some action, used for further browsing these results (multiple activities that use the results).

I can go to the home screen, start other applications etc. and when I return to my own application it just works correctly.

However, since the new Error Reporting feature I get some bug reports all related to a nullreference error. The object that is null is a reference to the static field in the mentioned separate class.

Since I cannot reproduce the bug I am inclined to think this is due to the application getting killed due to low memory, and when it relaunches it calls the oncreate from the activity that the user was currently in. However all the static data in the separate class is not restored and thus it crashes.

I would like to know: Is there a way to force the application to "restart" completely, and not start with the last used activity if it gets killed? Or is that standard behaviour? Can I do this programmatically? Like when the static fields are null, restart app?

+2  A: 

Restarting the activity where the user was is normal behaviour - the idea is to make it look to the user like the app was never closed. There are two things you can look at:

protected void onSaveInstanceState(Bundle outState){
    // This gets called by the system when it's about to kill your app
    // Put all your data in the outState bundle
}

That bundle is the same one that gets passed to the activity in onCreate(). You can then get any necessary information out of it and restore the values in the static class.

The other way is to simply check the values in the onResume() method of any of your activities. If the values are null or wrong in some way, then you can call start the original activity and finish() the one being started.

Steve H
Great. Looks like a good solution. For the time being I however resort to using `android:clearTaskOnLaunch` property on the main class, so it will always launch that activity and does the reloading. It's less pretty, but it fixes the bug for now hopefully.
Peterdk
Finally went with storing the static values directly into sharedpreferences, and when the values are null, retrieve them from these sharedpreferences. Now killing my app doesn't make it crash on restart.
Peterdk