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
您未提交新值
editor.putBoolean("mobile_flag",true).commit();
在SharedPreferences中完成变量的编辑后,需要提交更改。
editor.commit();
after using editor.putBoolean("mobile_flag",true);
you need to put editor.commit()
. This will save your sharedPreference otherwise nothing will be saved.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.