How to use SharedPreferences in Android to store, fetch and edit values


I want to store a time value and need to retrieve and edit it. How can I use SharedPreferences to do this?

12/14/2015 2:23:18 AM

Accepted Answer

To obtain shared preferences, use the following method In your activity:

SharedPreferences prefs = this.getSharedPreferences(
      "", Context.MODE_PRIVATE);

To read preferences:

String dateTimeKey = "";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

To edit and save preferences

Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();

The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:

<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory


I noticed, it is important to write difference between commit() and apply() here as well.

commit() return true if value saved successfully otherwise false. It save values to SharedPreferences synchronously.

apply() was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit. More detail is here.

9/14/2016 9:10:06 AM

To store values in shared preferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();

To retrieve values from shared preferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
    name = name + "  Sethi";  /* Edit the value here*/

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow