[英]how to set a shared preference
I am trying to set a shared preference but the below code results in false
on both occasions. 我试图设置一个共享的首选项,但是下面的代码在两种情况下都会导致
false
。
I first get the value of the flag when it doesn't exist and expect a false
. 当标志不存在时,我首先获取该标志的值,并期望为
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
. 但是,然后将值设置为
true
并再次获取标志,这一次我期望为true
但仍然为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);
使用
editor.putBoolean("mobile_flag",true);
you need to put editor.commit()
. 您需要放置
editor.commit()
。 This will save your sharedPreference otherwise nothing will be saved. 这将保存您的sharedPreference,否则将不保存任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.