Committing to a SharedPreferences Variable

2644 views android
6

I am trying to understand when is the value added to a SharedPreferences actually committed. Upon executing the code below, the initial value of the variable valCount is set to 0, to which 1 is then added with valCount+1. Meanwhile, the log.e method initially returns 0 (which is executed after the valCount+1 code). Only upon calling this code a second time will the value of the variable valCount be displayed as having a value of 1 when calling the log.e method.

    SharedPreferences.Editor editor = sharedPreferences.edit();
    valCount = sharedPreferences.getInt("valCount", 0);
    editor.putInt("valCount", valCount+1);
    editor.apply();
    Log.e("valCount", valCount+"");

Thank you. J

answered question

1 Answer

9

From the Android DOC for apply:

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.

So, this method saves your data async and if you'd like to save it synchronously you should use commit.

posted this

Have an answer?

JD

Please login first before posting an answer.