SharedPreferences:
This is one of the storage options available in Android. Used to store simple data in the form of key-value pair. Once the data is stored,it is permanently stored unless application data is cleared in this option. Session in apps can be maintained using this storage option only.To work with this, we have following steps.
To store:
1) Get SharedPreferences object by providing name and mode. modes can be
MODE_PRIVATE – only the same app can access
MODE_WORLD_READABLE – Apps that know the name of preference can read
MODE_WORLD_WRITABLE – Apps that know the name of preference can read and writeSharedPreferences sp = getSharedPreferences(“my_preferences”, Context.MODE_PRIVATE);
2) Get The Editor from SharedPreferences object
SharedPreferences.Editor editor = sp.edit();3) Put the data in key-value pair in editor
editor.putString(“name”, “Your name”);
editor.putInt(“id”, 321);4) Commit or apply the changes
editor.apply();
(or)
editor.commit();
To Retrieve:
1) Get SharedPreferences by passing name and mode. modes can be
MODE_PRIVATE – only the same app can access
MODE_WORLD_READABLE – Apps that know the name of preference can read
MODE_WORLD_WRITABLE – Apps that know the name of preference can read and writeSharedPreferences sp = getSharedPreferences(“my_preferences”, Context.MODE_PRIVATE);
2) Get individual values from SharedPreferences
String name = sp.getString(“name”, “any_default_string value”);
int id = sp.getInt(“id”, 1); // 1 is the default value hereCreate an android application to work with SharedPreferences
Refer source at