如何在 Android 中使用 SharedPreferences 存储布尔值? [英] How to store a boolean value using SharedPreferences in Android?

查看:58
本文介绍了如何在 Android 中使用 SharedPreferences 存储布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存布尔值,然后在 if-else 块中比较它们.

I want to save boolean values and then compare them in an if-else block.

我目前的逻辑是:

boolean locked = true;
if (locked == true) {
    /* SETBoolean TO FALSE */
} else {
    Intent newActivity4 = new Intent(parent.getContext(), Tag1.class);
    startActivity(newActivity4);
}

如何保存已设置为 false 的布尔变量?

How do I save the boolean variable which has been set to false?

推荐答案

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(); 
Boolean statusLocked = prefs.edit().putBoolean("locked", true).commit();

如果您不关心返回值(状态),那么您应该使用 .apply(),因为它是异步的,所以速度更快.

if you dont care about the return value (status) then you should use .apply() which is faster because its asynchronous.

prefs.edit().putBoolean("locked", true).apply();

让他们重新使用

Boolean yourLocked = prefs.getBoolean("locked", false);

而false为失败或未设置时的默认值

while false is the default value when it fails or is not set

在您的代码中,它看起来像这样:

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));
}

这篇关于如何在 Android 中使用 SharedPreferences 存储布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆