Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would SharedPreferences apply() and commit() fail?

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?

like image 949
Benjamin Fell Avatar asked Oct 29 '15 18:10

Benjamin Fell


People also ask

What is the difference between commit () and apply () method in SharedPreferences ()?

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.

What is the difference between apply () and commit () on the editor?

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.

What is the difference between getPreferences () and getSharedPreferences ()?

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.

Can we store large amount of data in SharedPreferences?

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.


1 Answers

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).

like image 161
Snild Dolkow Avatar answered Nov 12 '22 12:11

Snild Dolkow