zoukankan      html  css  js  c++  java
  • Android SharedPreferences存储map的方法

    在网上查了一些资料后,精简改写后得出自己想用的形式,记录一下

    public static void putHashMapData(Context context, String key, Map<String, String> datas) {
            JSONArray mJsonArray = new JSONArray();
                Iterator<Map.Entry<String, String>> iterator = datas.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) {
    
                    }
                }
                mJsonArray.put(object);
    
            SharedPreferences sp = context.getSharedPreferences("config",
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(key, mJsonArray.toString());
            editor.commit();
        }
    
        public static Map<String, String> getHashMapData(Context context, String key) {
    
            Map<String, String> datas = new HashMap<>();
            SharedPreferences sp = context.getSharedPreferences("config",
                    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);
                    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);
                            datas.put(name, value);
                        }
                    }
                }
            } catch (JSONException e) {
    
            }
    
            return datas;
        }
  • 相关阅读:
    attempted to return null from a method with a primitive return type (Double).
    window7 虚拟机安装
    DB 与oracle 批量新增的写法
    oracle 修改表
    备份还原oracle数据库
    oracle数据库的字符集更改
    IMP-00013
    oracle创建用户授权权限
    java中添加定时任务
    程序在运行过程中变量的保存位置与生命周期
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/9564062.html
Copyright © 2011-2022 走看看