Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between commit() and apply() in SharedPreferences

I am using SharedPreferences in my android app. I am using both commit() and apply() method from shared preference. When I use AVD 2.3 it shows no error, but when I run the code in AVD 2.1, apply() method shows error.

So what's the difference between these two? And by using only commit() can I store the preference value without any problem?

like image 341
Andro Selva Avatar asked May 11 '11 07:05

Andro Selva


People also ask

What difference between commit and apply?

commit() writes the data synchronously (blocking the thread its called from). It then informs you about the success of the operation. apply() schedules the data to be written asynchronously. It does not inform you about the success of the operation.

What is the method used to store and retrieve data on the SharedPreferences?

Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

How do I pass data from one activity to another using SharedPreferences?

How to pass data from one activity to another in Android using shared preferences? Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

Can we store large amount of data in SharedPreferences?

But you can also store a bit more complex data if you want. SharedPreferences are not intended to store a lot of data, there is no limit per se (since it is an xml file), but for larger sets of data, I would suggest using Room (or SQLite for the older projects).


1 Answers

apply() was added in 2.3, it commits without returning a boolean indicating success or failure.

commit() returns true if the save works, false otherwise.

apply() was added as the Android dev team noticed that almost no one took notice of the return value, so apply is faster as it is asynchronous.

http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()

like image 101
Ray Britton Avatar answered Oct 05 '22 11:10

Ray Britton