美文网首页
通过SharedPreferences将List<Map&

通过SharedPreferences将List<Map&

作者: Mr_不靠谱_先森 | 来源:发表于2017-03-20 14:29 被阅读107次
/**
 * Created by lzy on 2017/3/16.
 */

public class SensorUtil {
    /**
     * @param context
     * @param key
     * @param datas
     */
    public static void saveInfo(Context context, String key, List<Map<String, String>> datas) {
        JSONArray mJsonArray = new JSONArray();
        JSONObject object = new JSONObject();
        for (int i = 0; i < datas.size(); i++) {
            Map<String, String> itemMap = datas.get(i);
            Iterator<Map.Entry<String, String>> iterator = itemMap.entrySet().iterator();
            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("list", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, mJsonArray.toString());
        DebugLog.e(mJsonArray.toString());
        editor.commit();
    }

    /**
     * @param context
     * @param key
     * @return
     */
    public static List<Map<String, String>> getInfo(Context context, String key) {
        List<Map<String, String>> datas = new ArrayList<Map<String, String>>();
        SharedPreferences sp = context.getSharedPreferences("list", Context.MODE_PRIVATE);
        String result = sp.getString(key, "");

        DebugLog.e(result.toString()+"????????????????????????");

        //[{"071600000012":"{\"childlock\":true,\"co2\":\"55\",\"humidity\":\"66\",\"led\":true,\"level\":3,\"mac\":\"071600000012\",\"mode\":3,\"pm2.5\":\"22\",\"power\":true,\"ptc\":false,\"temp\":\"88\",\"temp_out\":\"99\"}"}]

        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;
    }
}

相关文章

网友评论

      本文标题:通过SharedPreferences将List<Map&

      本文链接:https://www.haomeiwen.com/subject/ieabnttx.html