Android SharedPreferences , how to save a simple int variable

donparalias picture donparalias · Apr 24, 2013 · Viewed 65.2k times · Source

I am trying for the last hour to save an integer in my Android application. I read that this can be done using the SharedPreferences. However i dont understand why it seems so confusing to do so.

How can i simply save an int variable ? And then when i run the application again , how can i interact with this variable again?

Answer

Blackbelt picture Blackbelt · Apr 24, 2013
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", yourIntValue);
editor.commit();

the you can get it as:

 SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
 int myIntValue = sp.getInt("your_int_key", -1);

The SharedPreference interface gives you access to the an xml file, and a easy way to modify it through its editor. The file is stored in /data/data/com.your.package/shared_prefs/ and you can access it onlu through this SharedPreference API