Commit vs. Apply
suggest changeThe editor.apply() method is asynchronous, while editor.commit() is synchronous.
Call either apply() or commit() after the edits.
SharedPreferences settings = getSharedPreferences(PREFS_FILE, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(PREF_CONST, true);
// This will asynchronously save the shared preferences without holding the current thread.
editor.apply();
SharedPreferences settings = getSharedPreferences(PREFS_FILE, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(PREF_CONST, true);
// This will synchronously save the shared preferences while holding the current thread until done and returning a success flag.
boolean result = editor.commit();
apply() was added in Android 2.3 (API 9). It writes without returning a boolean for success or failure.
commit() returns true if the save works, and false otherwise.
apply() updates the in-memory SharedPreferences immediately and starts an asynchronous write to disk. You are not notified of disk failures. If another editor calls commit() while an apply() is still outstanding, commit() blocks until the pending asynchronous commits finish, along with any other synchronous commits that are waiting.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents