如何存储使用共享preferences在Android的一个布尔值? [英] How to store a boolean value using SharedPreferences in Android?

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

问题描述

我要救布尔值,然后在if-else块进行比较。

我目前的逻辑是:

 布尔锁定= TRUE;

  如果(锁定==真){
                SETBoolean为FALSE
                }
            其他 {
            意图newActivity4 =新的意图(parent.getContext()
            Tag1.class);
    startActivity(newActivity4);

        }
 

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

解决方案

 共享preferences preFS = preferenceManager.getDefaultShared preferences();
prefs.edit()putBoolean(锁定,真).commit()。
 

让他们回到使用

 布尔yourLocked = prefs.getBoolean(锁定,假);
 

而假的是默认值失败或未设置时,

在你的code就应该是这样的:

 布尔锁定= TRUE;
共享preferences preFS = preferenceManager.getDefaultShared preferences();
如果(锁定){
//也许你想要得到的共享preferences进行检查。使用此,而是如果(锁定)
//如果(prefs.getBoolean(锁定,锁定){
   prefs.edit()putBoolean(锁定,真).commit()。
} 其他 {
   startActivity(新意图(parent.getContext(),Tag1.class));
}
 

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

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?

解决方案

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

to get them back use

Boolean yourLocked = prefs.getBoolean("locked", 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));
}

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

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