Saving Activity State in the onPause
Asked Answered
E

3

18

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

Ethnography answered 7/12, 2011 at 4:6 Comment(0)
T
39

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

Tribesman answered 7/12, 2011 at 4:38 Comment(0)
D
4

You can simply assign your variable foo to class member mFoo in onPause provided you also save mFoo in the state bundle in onSaveInstanceState. The same goes for the restore scenario.

Docilla answered 18/11, 2013 at 17:59 Comment(0)
C
0

If you choose to save the Activity state to Shared Preferences, you can check out the GNStateManager component of the library I wrote to make it easy to store and retrieve the required fields of the activity marked my @GNState annotation. It is dead simple to use. Other singleton class object states can be saved too. See here for Setup and Usage information: https://github.com/noxiouswinter/gnlib_android/wiki/gnstatemanager

Clay answered 3/11, 2014 at 2:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.