如何删除应用程序的SharedPreferences数据?
我正在创建一个使用大量web服务来同步数据的应用程序。出于测试目的,我需要在重新启动应用程序时删除一些SharedPreferences值。
如何删除应用程序的SharedPreferences数据?
我正在创建一个使用大量web服务来同步数据的应用程序。出于测试目的,我需要在重新启动应用程序时删除一些SharedPreferences值。
当前回答
要删除特定的值:SharedPreferences.Editor.remove()后面跟着一个commit()
SharedPreferences.Editor.clear()后面跟着一个commit()
如果您不关心返回值,并且从应用程序的主线程中使用它,请考虑使用apply()。
其他回答
没有一个答案适合我,因为我有很多共享的首选项键。
假设你正在运行一个Android测试,而不是一个单元测试。
它为我工作循环和删除通过所有shared_prefs文件。
@BeforeClass将在所有测试和ActivityTestRule之前运行
@BeforeClass
public static void setUp() {
Context context = InstrumentationRegistry.getTargetContext();
File root = context.getFilesDir().getParentFile();
String[] sharedPreferencesFileNames = new File(root, "shared_prefs").list();
for (String fileName : sharedPreferencesFileNames) {
context.getSharedPreferences(fileName.replace(".xml", ""), Context.MODE_PRIVATE).edit().clear().commit();
}
}
如果不需要每次都删除它,您可以手动从:
>应用程序->管理应用程序->(选择您的应用程序) ->清除数据或卸载
更新版本的Android:
设置—>应用程序—>(选择应用程序)—>存储—>清理数据 和清空缓存
从任意类中集中清除所有SharedPreferences:
public static SharedPreferences.Editor getEditor(Context context) {
return getPreferences(context).edit();
}
然后从任何类:(commit返回一个布尔值,你可以检查你的Preferences是否被清除)
Navigation.getEditor(this).clear().commit();
或者你可以用apply;返回为空
Navigation.getEditor(this).clear().apply();
试试下面的代码:
SharedPreferences sharedPreferences = getSharedPreferences("fake", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.clear().commit();
根据API 24(牛轧糖),你可以这样做:
context.deleteSharedPreferences("YOUR_PREFS");
然而,没有向后兼容性,所以如果你支持小于24的版本,请坚持使用:
context.getSharedPreferences("YOUR_PREFS", Context.MODE_PRIVATE).edit().clear().apply();