Setting a Boolean to null from SharedPreferences

Viewed 552

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?

2 Answers

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 */);

If you want to require a null return you can proceed through an object. It will be a solution to adjust and use the related control value (Boolean) in the object according to your operation. The parcelable process is required for your respective class.In the current situation, unfortunately returning null will not work. Since the default value expects a primitive type, it must be true or false.

Related