Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/212.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何存储ArrayList<;HashMap<;字符串,字符串>&燃气轮机;在共享参考中?_Android_Object_Arraylist_Sharedpreferences_Persistent Storage - Fatal编程技术网

Android 如何存储ArrayList<;HashMap<;字符串,字符串>&燃气轮机;在共享参考中?

Android 如何存储ArrayList<;HashMap<;字符串,字符串>&燃气轮机;在共享参考中?,android,object,arraylist,sharedpreferences,persistent-storage,Android,Object,Arraylist,Sharedpreferences,Persistent Storage,我希望在SharedReferences中存储一个包含Hashmap的ArrayList。我如何才能做到这一点?您可以将集合转换为json并将其存储在共享首选项中。每当需要获取数据时,只需获取字符串并将JSON转换回您的集合 //converting the collection into a JSON JSONArray result= new JSONArray(collection); SharedPreferences pref = getApplicationContext().get

我希望在SharedReferences中存储一个包含Hashmap的ArrayList。我如何才能做到这一点?

您可以将集合转换为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);
}

你试过这个吗?Johnathan Au请不要这样做。序列化数组很好,但将哈希映射放在数组中..如何将其转换回ArrayList?编辑我的答案以将JSON解析到集合中。此外,如果您想减少麻烦,您可以使用GSON
[
  "{test13=yeah3, test12=yeah2, test11=yeah1}",
  "{test23=yeah3, test22=yeah2, test21=yeah1}",
  "{test32=yeah2, test31=yeah1, test33=yeah3}"
]