如何删除应用程序的SharedPreferences数据?
我正在创建一个使用大量web服务来同步数据的应用程序。出于测试目的,我需要在重新启动应用程序时删除一些SharedPreferences值。
如何删除应用程序的SharedPreferences数据?
我正在创建一个使用大量web服务来同步数据的应用程序。出于测试目的,我需要在重新启动应用程序时删除一些SharedPreferences值。
当前回答
new File(context.getFilesDir(), fileName).delete();
我可以在共享首选项中删除文件
其他回答
要删除特定的值:SharedPreferences.Editor.remove()后面跟着一个commit()
SharedPreferences.Editor.clear()后面跟着一个commit()
如果您不关心返回值,并且从应用程序的主线程中使用它,请考虑使用apply()。
Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
没有一个答案适合我,因为我有很多共享的首选项键。
假设你正在运行一个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();
}
}
要删除一个特定的值,
SharedPreferences。编辑器删除(字符串键)后跟commit()或apply()
要删除所有值, SharedPreferences。编辑器clear()后面跟着commit()或apply()
清除它们:
PreferenceManager.getDefaultSharedPreferences(context).edit().clear().apply()