Java 清除 Android 中 SharedPreferences 中的首选项,而不仅仅是值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3630457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:56:28  来源:igfitidea点击:

Clearing preferences in SharedPreferences in Android, not just Values

javaandroidmobile

提问by Orca

from what I can incur out of the SharedPreferences documentation, I can update a preference, add one or clear all preference values in a shared preference file.

根据我可以从 SharedPreferences 文档中获得的内容,我可以更新首选项、添加一个或清除共享首选项文件中的所有首选项值。

But I want to completely clear everything inside a shared preference file, not just the values, but the preferences they refer to as well.

但是我想完全清除共享首选项文件中的所有内容,不仅是值,还包括它们所引用的首选项。

采纳答案by antonyt

If you have a SharedPreferences.Editorobject and you call clear(), does this not get you what you want? It will remove all preferences and if you call sharedPref.getAll()it should give you a map of size 0 [I just tested this].

如果你有一个SharedPreferences.Editor对象并且你调用clear(),这不是你想要的吗?它将删除所有首选项,如果您调用sharedPref.getAll()它,它应该会给您一个大小为 0 的地图 [我刚刚测试过这个]。

To remove one specific preference, call editor.remove(pref), where pref is the preference name.

要删除一个特定首选项,请调用editor.remove(pref),其中 pref 是首选项名称。

PS: Don't forget to commit your changes by calling commit() or apply() method on the editor. apply() is faster as it is asynchronous. commit() is synchronous but returns a boolean indicating if the commit succeeded.

PS:不要忘记通过在编辑器上调用 commit() 或 apply() 方法来提交更改。apply() 更快,因为它是异步的。commit() 是同步的,但返回一个布尔值,指示提交是否成功。

回答by QRohlf

you could try deleteFileto delete the sharedpreferences file in your app's private storage.

您可以尝试使用deleteFile删除应用私有存储中的 sharedpreferences 文件。

If you just want to delete the contents but not the file, calling .edit().clear().commit()should do it.

如果你只想删除内容而不是文件,调用.edit().clear().commit()应该这样做。

If just you want to delete one preference, calling .edit().remove("key").commit()should work.

如果您只想删除一个首选项,调用.edit().remove("key").commit()应该可以。