在android sharedpreferences中设置<String>不会在强制关闭时保存

Mal*_*lin 21 android sharedpreferences

我试图使用androids共享偏好,我记录了所有内容,下面的代码实际上提交了字符串集.问题是当我强制关闭应用程序并再次启动时,settings.getStringSet返回一个空集.没有任何错误消息.

我曾尝试过PreferenceManager.getDefaultSharedPreferences,但这对我也不起作用.

谢谢你的时间.

public static final String PREFS_NAME = "MyPrefsFile";
private static final String FOLLOWED_ROUTES = "followedRoutes";
Run Code Online (Sandbox Code Playgroud)

然后在保存时调用:

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();

}
Run Code Online (Sandbox Code Playgroud)

Rob*_*bbe 32

您也可以通过这种方式解决g00dy提到的错误:

从sharedPreferences获取集合并将其保存在变量中.

然后只需删除共享首选项中的集合,然后在保存时再次添加它.

SharedPreferences.Editor editor= sharedPref.edit();
editor.remove("mSet");
editor.apply(); 
editor.putStringSet("mSet", mSet);
editor.apply();
Run Code Online (Sandbox Code Playgroud)

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

  • 这节省了我的生命,希望它有更好的记录. (8认同)

g00*_*0dy 19

看看这里.

也用于参考:

SharedPreferences

SharedPreferences.Editor

编辑:

这个实际上有一个错误,请看这里.那里的摘录:

此问题仍存在于17 API级别.

这是因为SharedPreferences类的getStringSet()方法没有返回Set对象的副本:它返回整个对象,当您向其添加新元素时,SharedPrefencesImpl.EditorImpl类的commitToMemory方法会看到现有值等于前一个存储的值.

解决此问题的方法是复制SharedPreferences.getStringSet返回的Set,或使用始终更改的其他首选项强制写入内存(例如,每次存储集合大小的属性)

EDIT2:

有可能是一个解决方案在这里,一起来看看.