如何在 Android 中使用 SharedPreferences 存储布尔值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23919338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store a boolean value using SharedPreferences in Android?
提问by basti12354
I want to save boolean values and then compare them in an if-else block.
我想保存布尔值,然后在 if-else 块中比较它们。
My current logic is:
我现在的逻辑是:
boolean locked = true;
if (locked == true) {
/* SETBoolean TO FALSE */
} else {
Intent newActivity4 = new Intent(parent.getContext(), Tag1.class);
startActivity(newActivity4);
}
How do I save the boolean variable which has been set to false?
如何保存已设置为 false 的布尔变量?
回答by Emanuel S
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
Boolean statusLocked = prefs.edit().putBoolean("locked", true).commit();
if you dont care about the return value (status) then you should use .apply() which is faster because its asynchronous.
如果你不关心返回值(状态),那么你应该使用 .apply() ,它更快,因为它是异步的。
prefs.edit().putBoolean("locked", true).apply();
to get them back use
让他们重新使用
Boolean yourLocked = prefs.getBoolean("locked", false);
while false is the default value when it fails or is not set
而 false 是失败或未设置时的默认值
In your code it would look like this:
在您的代码中,它看起来像这样:
boolean locked = true;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
if (locked) {
//maybe you want to check it by getting the sharedpreferences. Use this instead if (locked)
// if (prefs.getBoolean("locked", locked) {
prefs.edit().putBoolean("locked", true).commit();
} else {
startActivity(new Intent(parent.getContext(), Tag1.class));
}