且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何存储使用共享preferences在Android的一个布尔值?

更新时间:2023-10-15 09:20:22

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