Android SharedPreferences保存Map集合

Android中数据存储方式:

1 使用SharedPreferences存储数据;
2 文件存储数据;
3 SQLite数据库存储数据;
4 使用ContentProvider存储数据;
5 网络存储数据;

在开发中根据项目需要,选取合适的数据存储方式。
借此文章,记录一下自己在开发中利用SharedPreferences存储Map集合的实现方式:

存:

public static SharedPreferences sp = MyApplication.getInstance().getSharedPreferences("SaveMap", Context.MODE_PRIVATE);
public static SharedPreferences.Editor editor =sp.edit();

public static void setMap(String key,LinkedHashMap<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);
        editor.putString(key, mJsonArray.toString());
        editor.commit();
    }

取:

public static LinkedHashMap<String, String> getMap(String key) {
        LinkedHashMap<String, String> datas = new LinkedHashMap<>();
        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) {
             e.printStackTrace();
        }
        return datas;
    }

应用:

LinkedHashMap<String,String> maps = new LinkedHashMap<>();
        maps.put("Training","1");
        maps.put("Action","2");
        maps.put("Weekly","3");
        UserInfoUtil.setMap("overMap",maps);
        LinkedHashMap<String,String> mapss = new LinkedHashMap<>();
        mapss = UserInfoUtil.getrMap("overMap");
        for (Map.Entry<String, String> entry : mapss.entrySet()) {
            String key = entry.getKey();
            Log.e("修改后Key = " ,""+key);
            String value = entry.getValue();
            Log.e("修改后Value = ",""+value);
        }

为保持有序,采用了LinkedHashMap,(LinkedHashMap:带双向链表的哈希表结构,保持存取顺序,允许null键和null值,非线程安全,效率较高)

你可能感兴趣的:(Android SharedPreferences保存Map集合)