android - SharedPreferences 值不会持续存在?

标签 android sharedpreferences

我有一个方法如下:

public static void addHighligtedDate(String date){
        prefs = context.getSharedPreferences(Fields.SHARED_PREFS_FILE, 0);
        Set<String> highlightedDates = prefs.getStringSet(Fields.HIGHLIGHTED_DATES, new HashSet<String>());
        highlightedDates.add(date);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putStringSet(Fields.HIGHLIGHTED_DATES, highlightedDates);
        editor.commit();
    }  

现在的场景是这样的:
当我打开应用程序添加要突出显示的日期时,它们会突出显示,因为 SharedPreferences 包含这些值。当我按下主页按钮退出应用程序并返回时,这些值仍然存在。

但是,当从最近使用的应用程序中删除该应用程序时,这些值就会消失。这是正常行为还是我做错了什么?

查看文档:

This data will persist across user sessions (even if your application is killed).

最佳答案

SharedPreferences 始终随应用程序卸载一起删除。

当您卸载任何应用程序时,该应用程序在您的内存中所做的所有更改都将被撤销,这意味着您的 SharedPreference 文件、其他数据文件、数据库文件、应用程序 会被 Android 操作系统自动删除.

检查 - how-to-remove-shared-preference-while-application-uninstall-in-android .

更新:

但是,当应用程序被终止或关闭时,SharedPreferences 中的值仍然存在。您的代码中存在一些问题。

将方法改为-

public static void addHighligtedDate(String date){
        prefs = context.getSharedPreferences(Fields.SHARED_PREFS_FILE, 0);
        Set<String> highlightedDates = prefs.
        getStringSet(Fields.HIGHLIGHTED_DATES, new HashSet<String>());
        highlightedDates.add(date);
        SharedPreferences.Editor editor = prefs.edit();
        editor.clear();
        editor.putStringSet(Fields.HIGHLIGHTED_DATES, highlightedDates);
        editor.commit();
    }  

更新:

public abstract Set getStringSet (String key, Set defValues)

Retrieve a set of String values from the preferences.

Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.

Parameters

key The name of the preference to retrieve.

defValues Values to return if this preference does not exist.

另请参阅引用 - sharedpreferences-does-not-save-on-force-close .

关于android - SharedPreferences 值不会持续存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24650870/

相关文章:

android - SharedPreferences 默认在应用程序第一次运行时未绑定(bind)

java - 我如何从图库中选择图像并在另一个 Activity 中显示该图像......?

java - android.view.InflateException : Binary XML file line #12: Binary XML file line #12: Error inflating class fragment

android - 首选项 Activity 设置更改不会坚持

Android SharedPreferences String Set - 一些项目在应用重启后被移除

java - 安卓工作室 : I need help in converting a code in java that returns an int from MYSQL database into a string (SHAREDPREFERENCES)

android - sharedpreferences 保存但在 if 语句上崩溃

android - 从谷歌地图获取 JSON 坐标

android - Google 登录 Android 应用程序以使用 Cloud Endpoints 后端

java - Android MotionLayout : How to handle both click and swipe events on same view?(包括视频示例)