SharedPreferences value is not updated

Juned picture Juned · Apr 17, 2012 · Viewed 48.4k times · Source

I am trying to update the values of SharedPreferences, here is my code:

edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putString(Settings.PREF_USERNAME+"",txtuser);
edit.putString(Settings.PREF_PASSWORD+"",txtpass);
edit.commit();" 

The problem is that when I am accessing this values, it is not returning updated values, it gives me a value of SharedPreferences.

But when I am confirming the data in XML file ,the data updated in that.

And after restarting my application I am getting that updated values. So it requires me to restart the application to get updated values.
So, how to get those updated values once it changes?

Thanks in advance

Here is my whole code:

@Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        ctx=this;

            status=PreferenceManager.getDefaultSharedPreferences(this).getString(Settings.PREF_STATUS, Settings.DEFAULT_STATUS);// get old value
        submit.setOnClickListener(new View.OnClickListener() {
          @Override
            public void onClick(View v) {

                  on(ctx,true);//  function will call and value is updated

                }
            }});    

     status=PreferenceManager.getDefaultSharedPreferences(this).getString(Settings.PREF_STATUS, Settings.DEFAULT_STATUS);// this should give me a updated value but gives old value

    }
    public static boolean on(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Settings.PREF_ON, Settings.DEFAULT_ON);
    }

    public static void on(Context context,boolean on) {
            if (on) Receiver.engine(context).isRegistered(); //
        }




**********in reciver file***********
public void isRegistered ) {
        Editor edit = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).edit();
        edit.putString(Settings.PREF_STATUS+"","0");
        edit.commit();
}

Answer

waqaslam picture waqaslam · Apr 17, 2012

Instead of using edit.commit();, you should use edit.apply();. Apply will update the preference object instantly and will save the new values asynchronously, so allowing you to read the latest values.


commit()