Wednesday, June 26, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...