我希望存储一个ArrayList,其中包含SharedPreferences中的Hashmap。我怎样才能做到这一点?如何在SharedPreferences中存储ArrayList <HashMap <String,String >>?
2
A
回答
4
您可以将您的收藏集转换为json并将其存储为共享首选项。无论何时您需要获取数据,只需获取字符串并将JSON转换回您的集合。
//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);
}
的JSON应该是这个样子:
[
"{test13=yeah3, test12=yeah2, test11=yeah1}",
"{test23=yeah3, test22=yeah2, test21=yeah1}",
"{test32=yeah2, test31=yeah1, test33=yeah3}"
]
+0
如何将它转换回ArrayList? – 2013-03-26 14:27:31
+0
编辑我的答案来解析JSON到集合。另外,如果你想减少麻烦,你可以使用GSON – Atrix1987 2013-03-27 11:16:39
你尝试过这个http://sudarmuthu.com/blog/using-preference-api-in-android-applications – 2013-03-26 04:30:10
@Johnathan金请不要这样做。序列化数组很好,但把哈希映射到它里面.. – minhaz 2013-03-26 04:30:36