Android笔记—通过SharedPreferences将List进行存储

懒得写了,查看个这个,复用轮子了 ,原文:http://blog.csdn.net/yijianhoan/article/details/44671171


其实归根到底还是将List<Map<String, String>>转成Json格式的字符串,然后通过SharedPreferences进行存储,方法如下:

1、保存方法

/**
 * 使用SharedPreferences存储List<Map<String, String>>
 *     存入
 * @param context
 * @param key
 * @param datas
 */
public void saveInfo(Context context, String key, List<Map<String, String>> datas) {
    JSONArray mJsonArray = new JSONArray();
    for (int i = 0; i < datas.size(); i++) {
        Map<String, String> itemMap = datas.get(i);
        Iterator<Map.Entry<String, String>> iterator = itemMap.entrySet().iterator();

        JSONObject object = new JSONObject();

        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            try {
                object.put(entry.getKey(), entry.getValue());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        mJsonArray.put(object);
    }

    SharedPreferences sp = context.getSharedPreferences("finals", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString(key, mJsonArray.toString());
    editor.commit();
}

2、取出方法

/**
 * 使用SharedPreferences存储List<Map<String, String>>
 *     取出
 * @param context
 * @param key
 * @return
 */
public List<Map<String, String>> getInfo(Context context, String key) {
    List<Map<String, String>> datas = new ArrayList<Map<String, String>>();
    SharedPreferences sp = context.getSharedPreferences("finals", Context.MODE_PRIVATE);
    String result = sp.getString(key, "");
    try {
        JSONArray array = new JSONArray(result);
        for (int i = 0; i < array.length(); i++) {
            JSONObject itemObject = array.getJSONObject(i);
            Map<String, String> itemMap = new HashMap<String, String>();
            JSONArray names = itemObject.names();
            if (names != null) {
                for (int j = 0; j < names.length(); j++) {
                    String name = names.getString(j);
                    String value = itemObject.getString(name);
                    itemMap.put(name, value);
                }
            }
            datas.add(itemMap);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return datas;
}

只要调用这两个方法进行存储和取出即可。

    原文作者:wjw_jack
    原文地址: https://blog.csdn.net/wjw_java_android/article/details/77934922
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞