views:

50

answers:

2

I have a variable that I would like to save and be able to restore when the viewer opens the app back up. I call this variable, count

private int count=0;

It changes every now and then through out my main activity. How can I save this after editing and changing it and be able to restore it?

A: 

Lookup SharedPreferences in the documentation.

EboMike
Could you explain how I could use this in my situation?
Keenan Thompson
on onResume, you open the shared preferences, load an int (say, PREFERENCE_COUNT, default value 0) and set `count` to it. In onPause, you open the shared preferences, open an editor, put `count` into PREFERENCE_COUNT, and commit.
EboMike
Thanks!!!!!!!!!
Keenan Thompson
If you like the answer, please accept it (and upvote it) - that way, we both get rep points.
EboMike
Sorry, can't up vote yet, but accepted it
Keenan Thompson
Thank you Keenan! And welcome to Stackoverflow :)
EboMike
Is what I posted as an answer right?
Keenan Thompson
Absolutely! Does it work?
EboMike
Ahh, yes! Thanks
Keenan Thompson
+1  A: 

Is this right?

protected void onResume(){
    super.onResume();
    SharedPreferences settings = getSharedPreferences(PREFS_COUNT, 0);
    count = settings.getInt("count", count);
}
protected void onPause(){
   super.onPause();


  SharedPreferences settings = getSharedPreferences(PREFS_COUNT, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putInt("count", count);
  editor.commit();
}
Keenan Thompson