logi0517
logi0517

Reputation: 845

Android sharedpreferences.getBoolean() returns the wrong, default value

enter image description here

On the picture you can see that the boolean variable took the default value, even though there was a key-value pair in the SharedPreferences with the right key. What can cause this? In the code this is at the end of an onCreate method. After this the onMapReady method gets called (from com.google.android.gms.maps.OnMapReadyCallback), where I check the SAME boolean value, to see If i have to place some markers on the map or not. In that method the getBoolean() behaviour is correct, the default value is ignored. This doesn't make any sense to me, anyone can help me out?

Upvotes: 2

Views: 7525

Answers (2)

Ishan Manchanda
Ishan Manchanda

Reputation: 479

1) Did you intend the space in the key "isThereReservation " ? In your debug code, the variable doesn't have a space. Make sure you use the right key else you'll get the default value!

2) How are you saving the sharedPref? your code should be:

myPrefs = myContext.getSharedPreferences("MY_PREFERENCE_NAME", MODE_PRIVATE);
myPrefEditor = myPrefs.edit();
myPrefsEditor.clear();
myPrefsEditor.putBoolean("MY_KEY",myBool);

and then you can access by using:

myPrefs = myContext.getSharedPreferences("MY_PREFERENCE_NAME", MODE_PRIVATE);
myPrefs.getBoolean("MY_KEY",MY_DEFAULT_VALUE);

Upvotes: 10

Ivan
Ivan

Reputation: 978

The method getBoolean return default value if the key doesn't exist. In your case, the default value is false and if the key of the SharedPreference doesn't exist is false in your case.

You are showing in debug the value of the HashMap mMap but what is the content of the eu.arrowhed.arrowheaddemo for the same key?

Upvotes: 1

Related Questions