Multiple instances of Sharedpreference give a different value for the same field

I'm trying to read the value of a field in sharedpreference using two different instances of sharepreferences. While reading using the first instance gives the correct result, a second read using the second instance returns the default values. Why is this so? Am I missing an important concept here?

code:

  public void testMethod(){

    SharedPreferences pref1=myContext.getSharedPreferences(PreferenceHelper.MY_PREF, myContext.MODE_PRIVATE);
    //Correct value is obtained here...
    String value1=pref1.getString("KEY", "");

    SharedPreferences pref2=myContext.getSharedPreferences(PreferenceHelper.MY_PREF, myContext.MODE_PRIVATE);
    //Incorrect value is obtained here...
    String value2=pref2.getString("KEY", "");

}

      

I doubt this is due to multiple instances of the same preference. Android documentation points out:

 Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other edits as soon as they are made.

      

Is my case related to the concept in this proposal?

+3


source to share


1 answer


Since you call commit () and don't apply (), one of them doesn't save and you get the wrong response. Check the docs:

Unlike commit (), which synchronously writes its preferences to persistent storage, apply () immediately commits its changes to SharedPreferences operations in memory, but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor of this SharedPreferences is doing a regular commit () and apply () is still inactive, commit () will block until all asynchronous transactions have completed, as well as the commit itself.



Above from http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply ()

+3


source







All Articles