Reputation: 9636
I am trying to set a shared preference but the below code results in false
on both occasions.
I first get the value of the flag when it doesn't exist and expect a false
. However, then I set the value to true
and fetch the flag again and this time I expect true
but it is still false
.
SharedPreferences sharedPref = getSharedPreferences("myapp",0);
//fetch value when it does not exist
Boolean mobileFlag = sharedPref.getBoolean("mobile_flag", false);
Log.d("mobileFlag1", mobileFlag+"");
//set the value
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("mobile_flag",true);
//fetch value when it has been set.
mobileFlag = sharedPref.getBoolean("mobile_flag", false);
Log.d("mobileFlag2", mobileFlag+"");
both times the results of the log messages is:
D/mobileFlag1﹕ false
D/mobileFlag2﹕ false
Upvotes: 0
Views: 60
Reputation: 3912
You need to commit your changes after you finish editing variables in your SharedPreferences.
editor.commit();
Upvotes: 2
Reputation: 9326
after using editor.putBoolean("mobile_flag",true);
you need to put editor.commit()
. This will save your sharedPreference otherwise nothing will be saved.
Upvotes: 1
Reputation: 73721
You didn't commit the new value
editor.putBoolean("mobile_flag",true).commit();
Upvotes: 3