Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/213.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java SharedReferences:为什么我的值没有被覆盖?_Java_Android_Boolean_Sharedpreferences - Fatal编程技术网

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

Java SharedReferences:为什么我的值没有被覆盖?,java,android,boolean,sharedpreferences,Java,Android,Boolean,Sharedpreferences,我正在尝试覆盖SharedReferences中的值。这是一个布尔值,但不知怎么的,它似乎有问题,或者我做错了什么。查看以下代码片段: sharedPref.edit().remove("bool1"); sharedPref.edit().putBoolean("bool1", true); sharedPref.edit().commit(); Log.v("TEST" ,"" + sharedPref.getBoolean("bool1", true)); 输出将是: 2020-01-2

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

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
我在网上找不到答案。有人知道吗?

每次调用时,它都会创建一个新对象,该对象有自己的键值对映射,然后您可以使用它来保存它们。当您再次调用
edit()
时,它将创建一个新对象,该对象将不具有您以前对该对象所做的编辑。相反,您可以这样做(所有这些方法都返回自身,以便您可以链接它们)

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

每次调用时,它都会创建一个新对象,该对象有自己的键值对映射,您可以将其保存或保留。当您再次调用
edit()
时,它将创建一个新对象,该对象将不具有您以前对该对象所做的编辑。相反,您可以这样做(所有这些方法都返回自身,以便您可以链接它们)


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

删除后也提交…?删除后也提交…?感谢您的回答!那么使用apply更好吗?是的,
apply()
异步写入磁盘,这样它就不会像
commit()
那样在写入磁盘时阻塞线程。谢谢您的回答!那么使用apply更好吗?是的,
apply()
异步写入磁盘,这样它就不会像
commit()
那样在写入磁盘时阻塞线程。
sharedPref.edit().putBoolean("bool1", true).commit();