uLYsseus
uLYsseus

Reputation: 1006

Can SharedPreferences.Editor.commit() be used multiple times within the same activity/fragment

So guys here is the question, I looked up at this one

http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#commit%28%29

and it mentions that "Note that when two editors are modifying preferences at the same time, the last one to call commit wins."

Say my activity is like this :

SharedPreferences.Editor editor();
    onCreate(....)
    {
       //start the instance of editor
    ......
      if(condition1)
        editor.put...
        editor.commit()

    }

    onPause()
    {
    if(condition1)
    {
      editor.commit()
    }
    }

Will this work? Because in my application I have to store the user credentials while online and do few submissions back to server, where the user id is recorded, when offline(i.e condition1), its not. The onPause is where i do it. So could anyone confirm this please. Thanks.

**The putBoolean() seems to work fine. this is a humongous code piece, so I might be doing a mistake somewhere with user credentials logic. So, I just want to confirm with editor.commit() usage.*

Upvotes: 1

Views: 1846

Answers (2)

Melquiades
Melquiades

Reputation: 8598

If you have a class member SharedPreferences.Editor editor, then yes, you can use it in your whole class without worry. Also, look at the method signature:

public abstract boolean commit()

You can check the result of commit to be sure the values have been written successfully.

boolean result = editor.commit();

Upvotes: 2

RocketSpock
RocketSpock

Reputation: 2081

Yes, in the majority of cases this will work in the example you have provided (work as in the correct order). If you want to absolutely make sure that the modifications are all performed then you can synchronize them..

For example:

private void someSaveMethod() {
    synchronized(this) {
        //TODO perform your retrieval of the PreferencesEditor
        editor.commit();
    }
}

Upvotes: 1

Related Questions