Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving Activity State in the onPause

I have a variable that I have successfully saved and restored using onSaveInstanceState

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState); // the UI component values are saved here.
    outState.putDouble("VALUE", liter);
    Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG).show();
}

But this only works if the activity is destroyed. I want to save the same variable by overriding the onPause() method and getting back when the activity is not not paused anymore any ideas on how to do this are greatly appreciated

like image 259
Waggoner_Keith Avatar asked Dec 07 '11 04:12

Waggoner_Keith


People also ask

How do you save an activity state?

When the activity goes into the background, the system calls onSaveInstanceState() . You should save the search query in the onSaveInstanceState() bundle. This small amount of data is easy to save. It's also all the information you need to get the activity back into its current state.

Why we should write the data saving code in the onPause () method?

onPause(): This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does very quickly, because the next activity will not be resumed until it returns.

How will you save and restore an instance state?

The onSaveInstanceState() method allows you to add key/value pairs to the outState of the app. Then the onRestoreInstanceState() method will allow you to retrieve the value and set it back to the variable from which it was originally collected.


1 Answers

As you have discovered, onSaveInstanceState is useful only in situations where you need to recreate the same so-called "instance" of the Activity after it has been destroyed by the OS, usually because it is too far in the back stack to stay alive under memory pressure.

Saving your data in onPause is indeed the way to go for persistence that lasts beyond a single execution of your Activity. To get this working, you have several options, including:

  • Shared Preferences
  • Files
  • Databases
  • Content Providers

I suggest reading this documentation to learn more about each of these options:

http://developer.android.com/guide/topics/data/data-storage.html

like image 198
lyricsboy Avatar answered Oct 23 '22 21:10

lyricsboy