How to store a boolean value using SharedPreferences in Android? How to store a boolean value using SharedPreferences in Android? android android

How to store a boolean value using SharedPreferences in Android?


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