Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple instance of Sharedpreference gives different value for same field

Tags:

android

I am trying to read the value of a field in sharedpreference using two different instances of sharepreferences. While read by using the first instance is giving the correct result, the second read operation using second instance is returning the default values.Why is it so?Am I missing some 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 am doubting this is due to multiple instances of the same preference.Android documentation states:

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

Does my case relates to concept in this sentence?

like image 939
pratim Avatar asked Oct 24 '25 10:10

pratim


1 Answers

Since your invoking commit() and not apply(), one of them isn't saving and you're getting the wrong answer. Check out the docs:

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. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

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

like image 118
The Hungry Androider Avatar answered Oct 26 '25 23:10

The Hungry Androider