out_sid3r
out_sid3r

Reputation: 1028

Android back key not letting me save activity state

Quick question. I have an activity that calls my save function at the proper moments, onPause and onSavedInstance. The onPause happens if the activity leaves the foreground and the onSavedInstance before being killed.

My activity saves the state perfectly if the user presses the "home" key but if he presses the "back" key the onPause still happens and consequently some fields are saved in the activity class attributes.

The problem is that when the User goes back to the activity the onCreate is called meaning (for what I understood) that the class is instantiated and therefore its attributes are null again. If the onSavedInstance was called when the back key was previously pressed I could use it to save the activity state but it's not.

So my question is, when the user presses the back key how can I save the activity sate withou using sqlite, file saving and other persistance methods?

Upvotes: 1

Views: 1552

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006614

When the user presses the BACK button, your foreground activity is destroyed. That activity will be called with onPause(), onStop(), and onDestroy(). That activity object will then be garbage collected (unless you introduced a memory leak).

onSaveInstanceState() will be called periodically if there is a chance that the activity will be destroyed shortly but in a way where the user might be able to navigate back to it. The prominent case for this is during a configuration change, such as rotating the screen.

What you should be doing in onPause(), if anything, is persisting data using "sqlite, file saving and other persistance methods". Once onPause() is called, there are no guarantees that this activity will stick around, or that your entire process will stick around. Anything you value, therefore, should get written out to persistent storage.

The "state" for onSaveInstanceState() would be things that affect the activity's UI but are not part of the persistent data model. Much of this is handled for you automatically by Android's built-in implementation of that method (e.g., the text in an EditText), but you can add your own information to the Bundle if you wish. However, your instance state is not your data model, so anything you want to stick around needs to be written out to persistent storage.

If your concern is performance, you are welcome to cache data in static data members/singletons, assuming you do not introduce a memory leak. But, again, once onPause() is called, your process may be terminated at any point in time. Your static data members can only be a cache; your data model must be something persistent.

Upvotes: 1

Related Questions