设置<字符串>在Android的共享preferences不保存强制关闭字符串、不保存、LT、GT

2023-09-06 02:41:49 作者:专属的偏见

我试着去使用共享preferences机器人,从来就记录了一切,低于code真的犯字符串集。问题是,当我强行关闭应用程序,并重新启动,则settings.getStringSet返回一个空集。没有errormessages任何地方。

从来就试图preferenceManager.getDefaultShared preferences但对我来说,要么不工作。

感谢您的时间。

 公共静态最后弦乐preFS_NAME =我的prefsFile;
私有静态最后弦乐FOLLOWED_ROUTES =followedRoutes;
 

和后来当保存被称为:

 公共无效onFollowClicked(查看视图){

共享preferences设置= getShared preferences(preFS_NAME,MODE_PRIVATE);
共享preferences.Editor编辑器= settings.edit();

设置<字符串>如下= settings.getStringSet(FOLLOWED_ROUTES,新的HashSet<字符串>());
follows.add(routeId);

editor.putStringSet(FOLLOWED_ROUTES,如下);
editor.commit();

}
 

解决方案

看看here.

也为REFFERENCE:

Shared$p$pferences

Shared$p$pferences.Editor

编辑:

实际上有与这一个错误,请参阅这里。从那里摘录:

  Android C NDK中如何操作字符串数据类型呢

此问题仍然present在17 API级别。

     

这是由于因的getStringSet()方法   共享preferences类不返回集合对象的副本:它   返回整个对象,当你添加新的元素吧,   共享prefencesImpl.EditorImpl类commitToMemory方法见   该现有值等于存储在previous之一。

     

要解决这个问题的办法是使复印件一套   通过共享preferences.getStringSet退回或强制写入   存储器使用其它preference总是改变(例如,一个   属性存储该组的每个时间的大小)

EDIT2:

有可能是一个溶液here,一起来看看。

Im trying to use androids sharedpreferences, I´ve logged everything and the code below really commits the string set. The problem is when I force close the app and start again, the settings.getStringSet returns an empty set. No errormessages anywhere.

I´ve tried PreferenceManager.getDefaultSharedPreferences but that does not work for me either.

Thanks for you time.

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

and later on when saved is called:

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

}

解决方案

Take a look here.

Also for refference:

SharedPreferences

SharedPreferences.Editor

EDIT:

There's actually a bug with this one, see here. An extract from there:

This problem is still present on the 17 API level.

It is caused because the getStringSet() method of the SharedPreferences class doesn't return a copy of the Set object: it returns the entire object and, when you add new elements to it, the commitToMemory method of the SharedPrefencesImpl.EditorImpl class see that the existing value is equal to the previous one stored.

The ways to workaround this issue is to make a copy of the Set returned by SharedPreferences.getStringSet or force the write to memory using other preference that always change (for example, a property that stores the size of the set each time)

EDIT2:

There might be a solution here, take a look.