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

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


当前回答

Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();

其他回答

要从首选项中删除键-值对,可以轻松执行以下操作

getActivity().getSharedPreference().edit().remove("key").apply();

我还开发了一个库,用于方便地操作共享首选项。你可以找到下面的链接

https://github.com/farruhha/SimplePrefs

一行删除Android共享首选项:-)

context.getSharedPreferences("YOUR_PREFS", 0).edit().clear().commit();

或申请非阻塞异步操作:

this.getSharedPreferences("YOUR_PREFS", 0).edit().clear().apply();

在类定义中:

private static final String PREFERENCES = "shared_prefs";

private static final SharedPreferences sharedPreferences  = getApplicationContext().getSharedPreferences(PREFERENCES, MODE_PRIVATE);

类内部:

public static void deleteAllSharedPrefs(){
    sharedPreferences.edit().clear().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();
    }
}

如果不需要每次都删除它,您可以手动从:

>应用程序->管理应用程序->(选择您的应用程序) ->清除数据或卸载

更新版本的Android:

设置—>应用程序—>(选择应用程序)—>存储—>清理数据 和清空缓存