Muhammad Maqsoodur Rehman Muhammad Maqsoodur Rehman - 8 months ago 38
Android Question

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

to do this?


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.