微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐