如何删除应用程序的SharedPreferences数据?

我正在创建一个使用大量web服务来同步数据的应用程序。出于测试目的,我需要在重新启动应用程序时删除一些SharedPreferences值。


当前回答

芬兰湾的科特林:

  var prefs2: SharedPreferences? = context!!.getSharedPreferences("loginFB", 0)
  prefs2!!.edit().remove("email").commit()

其他回答

要删除特定的值:SharedPreferences.Editor.remove()后面跟着一个commit()

SharedPreferences.Editor.clear()后面跟着一个commit()

如果您不关心返回值,并且从应用程序的主线程中使用它,请考虑使用apply()。

你也可以用你的设备手动卸载你的应用。然后,当你重新安装应用程序时,共享首选项已被重置。

对于Kotlin用户来说,这相当简单:

val sharedPref = context.getSharedPreferences("myPref", Context.MODE_PRIVATE)
 sharedPref.edit().clear().apply()

你总可以用程序来做就像这里其他答案所建议的那样。但是出于开发目的,我发现这个插件非常有用,因为它大大加快了我的开发速度。

插件:ADB Idea

它为您提供了功能,以清除应用程序数据和撤销权限从您的Android工作室本身,只需点击一个按钮。

没有一个答案适合我,因为我有很多共享的首选项键。

假设你正在运行一个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();
    }
}