Moe Zus
Moe Zus

Reputation: 33

How to save state of activity on android on back key press

I'm having an issue with an android app I'm writing that seems like it should be a common issue but I can't find any information on it.

I have a scoreboard activity in my app that just stores a grid of scores in textviews, it's the kind of thing that the user will update, then hit the back key and look at some other activities, then come back later to update it, leave again, etc...

The problem is that every time they leave and come back the whole activity gets reset, losing all their scores. I can't use saveInstanceState because it isn't called on back key pressed. I really don't know where to go from here except for saving thew hole grid in sharedpreferences, I feel like there has got to be a better way though

Any ideas?

Upvotes: 1

Views: 2863

Answers (2)

Bhavin Nattar
Bhavin Nattar

Reputation: 3215

May this help you

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.

Upvotes: 1

Knossos
Knossos

Reputation: 16038

In general, you need to save any state information in onPause(), and recover it in onResume().

I was under the impression that various state information is kept automatically when you close the App, and automatically restores itself when start it back up again (until Android removes the App from its memory to make space, calling onDestroy()).

If I were you, I would store the grid in SharedPreference. It really is the most reliable solution.

You can also use the details in this topic: https://stackoverflow.com/a/151940/503508

Upvotes: 1

Related Questions