2

我希望在 SharedPreferences 中存储一个包含 Hashmap 的 ArrayList。我怎样才能做到这一点?

4

1 回答 1

5

您可以将您的收藏转换为 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}"
]
于 2013-03-26T06:23:25.217 回答