I'm using SharedPreferences to persist user's data in my application.
I know the difference between commit()
and apply()
methods, but I've noticed that commit()
returns true if the new values were successfully written to persistent storage and apply()
does not.
What are the reasons that could cause a commit()
method to return false or a apply()
method to fail?
Unlike commit() , which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures.
Use apply(). It writes the changes to the RAM immediately and waits and writes it to the internal storage(the actual preference file) after. Commit writes the changes synchronously and directly to the file. Save this answer.
getSharedPreferences() — Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context in your app. getPreferences() — Use this from an Activity if you need to use only one shared preference file for the activity.
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). There is also another reason why storing in a database makes more sense.
Let's take a look at the source code for commit():
public boolean commit() {
MemoryCommitResult mcr = commitToMemory();
SharedPreferencesImpl.this.enqueueDiskWrite(
mcr, null /* sync write on this thread okay */);
try {
mcr.writtenToDiskLatch.await();
} catch (InterruptedException e) {
return false;
}
notifyListeners(mcr);
return mcr.writeToDiskResult;
}
In other words, commit()
will return false if the thread is interrupted while waiting for the disk write to finish, or if the disk write fails for some reason (most likely because the disk was full).
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