Search code examples
javaandroidsharedpreferences

Setting a Boolean to null from SharedPreferences


I am using SharedPreferences to store user settings/options.

I have added a new option that can be on or off and so want to store this as a boolean in my shared preferences file.

That is all good, however as this is a new option I want to set my internal variable to null if the option hasn't been explicitly set by the user (this way I can prompt for their choice when the new version is run for the first time).

The following doesn't work because getBoolean expects the primitive boolean as the default value to return if the preference isn't foudn in shared+prefs.

myNewSetting = shared_prefs.getBoolean("my_mew_setting",null);

In the above myNewSetting is a Boolean which can be set to null, but this doesn't help because of getBooleans requirements.

Is there any way around this?


Solution

  • The method getBoolean returns a primitive boolean, so even you assign it to a Boolean, it just boxes it. The definition of the method is:

    abstract boolean getBoolean(String key, boolean defValue)

    If you really want to distinguish the case where the settings does not exist, just check if it is present or not:

       if (!shared_prefs.contains("my_mew_setting"))
          myNewSetting = null;
       else
          myNewSetting = shared_prefs.getBoolean("my_mew_setting", true /* never use default value in this code because of the if condition */);