Keenan Thompson
Keenan Thompson

Reputation: 980

Saving Variables (Android)

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?

Upvotes: 3

Views: 2526

Answers (2)

Keenan Thompson
Keenan Thompson

Reputation: 980

Using this...

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();
}

Upvotes: 4

EboMike
EboMike

Reputation: 77762

Lookup SharedPreferences in the documentation.

Upvotes: 3

Related Questions