Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

if statement - How to store a boolean value using SharedPreferences in Android?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...