从 SharedPreferences 将布尔值设置为 null

Setting a Boolean to null from SharedPreferences

我正在使用 SharedPreferences 来存储用户 settings/options。

我添加了一个可以打开或关闭的新选项,因此想将其作为 boolean 存储在我的共享首选项文件中。

这一切都很好,但是因为这是一个新选项,如果用户没有明确设置该选项,我想将我的内部变量设置为 null(这样我可以提示他们新版本第一次运行时的选择)。

以下内容不起作用,因为如果 shared+prefs.

中未找到首选项,getBoolean 期望原语 boolean 作为 return 的默认值
myNewSetting = shared_prefs.getBoolean("my_mew_setting",null);

上面的myNewSetting是一个Boolean可以设置为null,但这没有用,因为getBoolean的要求。

有什么解决办法吗?

方法 getBoolean returns 一个原始布尔值,因此即使您将它分配给一个布尔值,它也只是将其框起来。方法的定义是:

abstract boolean getBoolean(String key, boolean defValue)

如果真的要区分设置不存在的情况,只看有没有:

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

如果您想要一个 null return,您可以通过一个对象继续。根据您的操作调整和使用对象中的相关控制值(布尔值)将是一个解决方案。您各自的 class.In 当前情况需要 parcelable 过程,不幸的是 returning null 将不起作用。由于默认值需要原始类型,因此它必须是 true 或 false。