Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a boolean value using SharedPreferences in Android?

Tags:

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?

like image 287
basti12354 Avatar asked May 28 '14 18:05

basti12354


People also ask

Which method is used to retrieve a Boolean value from a SharedPreferences object?

Get bool data This method getBool returns a boolean value from the SharedPreferences.

How do you use SharedPreferences in Android to store fetch and edit values?

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); String restoredText = prefs. getString("text", null); if (restoredText != null) { String name = prefs. getString("name", "No name defined");//"No name defined" is the default value.

What is the method used to store and retrieve data on the SharedPreferences?

Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

Can we store objects in SharedPreferences?

We can store fields of any Object to shared preference by serializing the object to String. Here I have used GSON for storing any object to shared preference.


1 Answers

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)); } 
like image 107
Emanuel S Avatar answered Oct 23 '22 15:10

Emanuel S