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?
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.
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 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.
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).
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With