我正在尝试使用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();
}
发布于 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)
}
https://stackoverflow.com/questions/17469583
复制相似问题