SharedPreferences:为什么我的值没有被覆盖?

SharedPreferences: Why is my value not overwritten?

我正在尝试覆盖 SharedPreferences 中的值。这是一个布尔值,但不知何故它似乎有问题,或者我做错了什么。看看这个小代码片段:

sharedPref.edit().remove("bool1");
sharedPref.edit().putBoolean("bool1", true);
sharedPref.edit().commit();
Log.v("TEST" ,"" + sharedPref.getBoolean("bool1", true));

输出将是:

2020-01-26 19:37:48.244 29886-29886/de.rich.richquotes.richquotes V/TEST: false

我在互联网上找不到这方面的答案。有人知道吗?

每次调用 sharedPref.edit(), it creates a new SharedPreferences.Editor object, which has its own map of key-value pairs which you can then commit() or apply() 来保存它们。当您再次调用 edit() 时,它将创建一个新对象,该对象不会包含您之前对对象所做的编辑。相反,你可以做这样的事情(所有这些方法 return 本身所以你可以链接它们)

sharedPref.edit().putBoolean("bool1", true).commit();

此外,如果您不关心提交是否成功,您应该使用apply()。它是异步的,但也会立即在内存中进行更改,因此您不会注意到任何差异。