Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 822
Keenan Thompson Avatar asked Jul 16 '26 16:07

Keenan Thompson


2 Answers

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();
}
like image 199
Keenan Thompson Avatar answered Jul 19 '26 07:07

Keenan Thompson


Lookup SharedPreferences in the documentation.

like image 45
EboMike Avatar answered Jul 19 '26 07:07

EboMike