Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save app on back button press

Tags:

android

How can I store the state of my app when back button is pressed.

When back button is pressed only onPause() is called but not onSaveInstanceState where we can store our data in outState bundle.

One answer may be sharedPreference but my problem is it will store only int and not intArray as bundles does.

Is there any way to explicitly call onSaveInstanceState?

like image 382
Nitesh V Avatar asked Mar 10 '11 23:03

Nitesh V


2 Answers

user 600027... Even if you were able to call onSaveInstanceState the bundle would not be persisted and I do not believe it would be available after a hard kill. You could write a method to convert an array of ints to set of strings and then persist the data by calling putStringSet() and then write a method to covert a set of strings to an array of ints.

JAL

like image 62
JAL Avatar answered Sep 19 '22 18:09

JAL


You can do normal saving in Activity#onDestroy().

I think the intention behind onCreate(Bundle), onSaveInstanceState(Bundle) and onRestoreInstanceState(Bundle) is to provide for a chance for you to save state before being killed in the background. The app should then recover and appear to the user as if nothing happened.

On a back button press the user is in some sense "finished" with the activity. The amount of data that should be saved is different. Yes, it would be a good idea to save your state in SharedPreferences in this case.

like image 23
Matthew Willis Avatar answered Sep 19 '22 18:09

Matthew Willis