首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >android共享首选项中的Set<String>不会在强制关闭时保存

android共享首选项中的Set<String>不会在强制关闭时保存
EN

Stack Overflow用户
提问于 2013-07-04 19:52:37
回答 1查看 15.3K关注 0票数 22

我正在尝试使用androids共享首选项,我已经记录了所有内容,下面的代码确实提交了字符串集。问题是,当我强制关闭应用程序并重新启动时,settings.getStringSet返回一个空集。任何地方都没有错误消息。

我试过PreferenceManager.getDefaultSharedPreferences,但它对我也不起作用。

感谢您的宝贵时间。

public static final String PREFS_NAME = "MyPrefsFile";
private static final String FOLLOWED_ROUTES = "followedRoutes";

稍后,当调用saved时:

public void onFollowClicked(View view){

SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();

Set<String> follows =  settings.getStringSet(FOLLOWED_ROUTES, new HashSet<String>());
follows.add(routeId);

editor.putStringSet(FOLLOWED_ROUTES, follows);
editor.commit();

}
EN

回答 1

Stack Overflow用户

发布于 2014-10-11 22:33:36

您还可以通过以下方式解决g00dy提到的错误:

从sharedPreferences获取集合,并将其保存在一个变量中。

然后,在保存时再次添加之前,只需删除sharedpreferences中的集合即可。

SharedPreferences.Editor editor= sharedPref.edit();
editor.remove("mSet");
editor.apply(); 
editor.putStringSet("mSet", mSet);
editor.apply();

确保使用apply()或commit()两次。

或者,如果您在Kotlin中工作,只需:

PreferenceManager.getDefaultSharedPreferences(applicationContext)
    .edit {
        this.remove("mSet")
        this.apply()
        this.putStringSet("mSet", mSet)
    }
票数 34
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17469583

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档