How to store a boolean value using SharedPreferences in Android?
Asked Answered
A

1

23

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?

Azrael answered 28/5, 2014 at 18:35 Comment(0)
W
69
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // getActivity() for Fragment
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));
}
Warenne answered 28/5, 2014 at 18:37 Comment(7)
where I have to put this? To the if-statement?Azrael
@Emanuel: Beware: you have to commit your writes to the SharedPreferences. Also make sure you open an editor on it!Pinkston
Check my source ;-) check carefully at true)->commit()<- Ive fixed the typo at prefs.edit(), thx for the hintWarenne
In API level 9 or higher, you should usually prefer apply() over commit(), see developer.android.com/reference/android/content/…Ironmaster
There is a bool xml type if you need to store in xmlJaunita
prefs.getBoolean() always returns boolean primitive -> no need in autoboxing here -> just use boolean instead of Boolean.Dolan
I had to add getApplicationContext in SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());Matte

© 2022 - 2024 — McMap. All rights reserved.