[英]how to set a shared preference
我试图设置一个共享的首选项,但是下面的代码在两种情况下都会导致false
。
当标志不存在时,我首先获取该标志的值,并期望为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+"");
两次日志消息的结果均为:
D/mobileFlag1﹕ false
D/mobileFlag2﹕ false
您未提交新值
editor.putBoolean("mobile_flag",true).commit();
在SharedPreferences中完成变量的编辑后,需要提交更改。
editor.commit();
使用editor.putBoolean("mobile_flag",true);
您需要放置editor.commit()
。 这将保存您的sharedPreference,否则将不保存任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.