Search code examples
androidsharedpreferencesandroid-fileandroid-frameworkperformance

Ensure correct write-back of SharedPreference


I'm using SharedPreferences to persists Object fields. Take this example:

class Item {

    private String note;

    public void setNote(String newNote) {
        this.note = newNote;
        update();
    }

    private void update() {
        String json = ....; // create JSON image of the object

        Editor editor = App.getAppPrefs().edit(); // Load SharedPreferences editor
        editor.putString("exampleItem", json);
        editor.apply();
    }

setNote() (and thus update()) is called everytime a "Note"-EditText is changed.

Now I have several questions: How can I verify that the newest version of "note" is saved? Is the possibility that the last call is overriden by an earlier call to editor? How can I minimize the workload? There has to be some smarter, lighter way than calling apply() 100x for a 100 char text.


Solution

  • You can simply use synchronized it will help thread to wait until old thread complete its work for update.

    private synchronized void update() {
    }