Search code examples
androidandroid-sharedpreferences

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?


Solution

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