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

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


当前回答

似乎所有的解决方案都不是完全有效或死亡

清除活动中的所有SharedPreferences

PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().clear().apply();

从onCreate之后的Main Activity调用这个

注:我使用了.apply()而不是.commit(),你可以自由选择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 preferences = getSharedPreferences("Mypref", 0);
preferences.edit().remove("text").commit();

今早刚做过。从命令提示符:

adb shell
cd /data/data/YOUR_PACKAGE_NAME/shared_prefs
rm * // to remove all shared preference files
rm YOUR_PREFS_NAME.xml // to remove a specific shared preference file

注意:这需要一个根设备,如库存Android虚拟设备,Genymotion设备,或一个实际根手机/平板电脑等。

根据API 24(牛轧糖),你可以这样做:

context.deleteSharedPreferences("YOUR_PREFS");

然而,没有向后兼容性,所以如果你支持小于24的版本,请坚持使用:

context.getSharedPreferences("YOUR_PREFS", Context.MODE_PRIVATE).edit().clear().apply(); 

你可以使用preferences.edit().remove("key").commit()从共享首选项中删除保存的值。