How can I store an ArrayList<HashMap<String, String>> in SharedPreferences?

时间秒杀一切 提交于 2019-12-06 05:04:29

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}"
]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!