如何存储 ArrayList<HashMap<String, String>>在共享首选项中? [英] How can I store an ArrayList<HashMap<String, String>> in SharedPreferences?
本文介绍了如何存储 ArrayList<HashMap<String, String>>在共享首选项中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望在 SharedPreferences 中存储一个包含 Hashmap 的 ArrayList.我该怎么做?
解决方案
您可以将您的集合转换为 json 并将其存储在共享首选项中.每当您需要获取数据时,只需获取字符串并将 JSON 转换回您的集合即可.
//将集合转换成JSONJSONArray 结果= new JSONArray(collection);SharedPreferences pref = getApplicationContext().getSharedPreferences(PREF_NAME, 0);//将字符串存储在pref文件中SharedPreferences.Editor prefEditor = pref.edit();prefEditor.putString(KEY, result.toString());prefEditor.commit();//从pref获取JSONString storedCollection = pref.getString(KEY, null);//解析字符串以填充您的集合.ArrayList>collection = new ArrayList>();尝试 {JSONArray 数组 = 新的 JSONArray(storedCollection);HashMap<字符串,字符串>项目 = 空;for(int i =0; i它 = ary.keys();item = new HashMap();而(it.hasNext()){String key = it.next();item.put(key, (String)ary.get(key));}集合.添加(项目);}} catch (JSONException e) {Log.e(TAG, "同时解析", e);}
JSON 应该如下所示:
<预><代码>["{test13=yeah3, test12=yeah2, test11=yeah1}","{test23=yeah3, test22=yeah2, test21=yeah1}",{test32=yeah2,test31=yeah1,test33=yeah3}"]I wish to store an ArrayList which contains Hashmap inside SharedPreferences. How can I do this?
解决方案
You can convert your collection into a json and store it in shared preference. Whenever you need to get the data, just get the string and convert the JSON back into your collection.
//converting the collection into a JSON
JSONArray result= new JSONArray(collection);
SharedPreferences pref = getApplicationContext().getSharedPreferences(PREF_NAME, 0);
//Storing the string in pref file
SharedPreferences.Editor prefEditor = pref.edit();
prefEditor.putString(KEY, result.toString());
prefEditor.commit();
//Getting the JSON from pref
String storedCollection = pref.getString(KEY, null);
//Parse the string to populate your collection.
ArrayList<HashMap<String, String>> collection = new ArrayList<HashMap<String, String>>();
try {
JSONArray array = new JSONArray(storedCollection);
HashMap<String, String> item = null;
for(int i =0; i<array.length(); i++){
String obj = (String) array.get(i);
JSONObject ary = new JSONObject(obj);
Iterator<String> it = ary.keys();
item = new HashMap<String, String>();
while(it.hasNext()){
String key = it.next();
item.put(key, (String)ary.get(key));
}
collection.add(item);
}
} catch (JSONException e) {
Log.e(TAG, "while parsing", e);
}
The JSON should look something like this:
[
"{test13=yeah3, test12=yeah2, test11=yeah1}",
"{test23=yeah3, test22=yeah2, test21=yeah1}",
"{test32=yeah2, test31=yeah1, test33=yeah3}"
]
这篇关于如何存储 ArrayList<HashMap<String, String>>在共享首选项中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文