我尝试保存/恢复一组字符串,除了一件事之外,所有操作都正常。当我创建我的字符串时,我把:
Set<String> set = new HashSet<String>();
for(int i=0; i<toggles.size();i++){
set.add(toggles.get(i).serialise());
}
顺序例如是“蓝牙”、“应用”、“数据”。当我回来的时候:
Set<String> set = prefs.getStringSet(key, new HashSet<String>());
for (String toggle : set){
Toggle t = new Toggle();
t.deserialize(toggle);
toggles.add(t);
}
我得到“应用程序”“蓝牙”“数据”,他们是按名称排序的,我不想要这个。我想要得到与保存的订单相同的订单。有人能帮我吗?
发布于 2012-11-19 09:04:15
这是不可能的。集合是无序集合。
发布于 2012-11-19 16:15:56
您可以用数字作为字符串的前缀,例如00application
、01bluetooth
、02data
,按照您想要取出它们的顺序。将从getStringSet
返回的Set<String>
放入Array<Set>
中并对其进行排序。
Set<String> set = prefs.getStringSet(key, new HashSet<String>());
Array<String> a = set.toArray();
java.util.Arrays.sort(a);
发布于 2017-07-11 21:26:16
您可以将字符串列表保存为带有分隔符的单个字符串。例如,这是您的数组:
["Italy", "France", "Spain", "Japan", "United States"]
您可以将其另存为:
"Italy;France;Spain;Japan;United States"
在代码中:
SharedPreferences sharedPref = mContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();
// countries is your List
String countriesString = TextUtils.join(";", countries);
editor.putString("countries", countriesString);
editor.apply();
要检索数据,请执行以下操作:
final String countriesString = sharedPref.getString("countries", "");
List<String> countries = new ArrayList<>();
if (!countriesString.isEmpty()){
countries = new ArrayList<>(Arrays.asList(countriesString.split(";")));
}
https://stackoverflow.com/questions/13446367
复制相似问题