Android SharedPreferences , how to save a simple int variable

android, sharedpreferences

Solution

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

Problem

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?

Original source

Related problems