Wednesday 26 June 2019

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?


Answer



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




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


To read preferences:



String dateTimeKey = "com.example.app.datetime";

// 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:




/samples/android-/ApiDemos directory


Edit==>



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...