本文主要是介绍SharedPreferences存储 list map,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1通过SharedPreferences将List<Map<String, String>>进行存储
保存数据
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<Entry<String, String>> iterator = itemMap.entrySet().iterator();JSONObject object = new JSONObject();while (iterator.hasNext()) {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);Editor editor = sp.edit();editor.putString(key, mJsonArray.toString());editor.commit();}
2 取数据
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;}
2通过SharedPreferences将Map<String, String>进行存储
1 先保存成json
public static JSONObject getMaptojson(Map<String, String> map) {Map<String, String> params = new HashMap<String, String>();JSONObject json = new JSONObject();try {Iterator iter = map.entrySet().iterator();while (iter.hasNext()) {Map.Entry entry = (Map.Entry) iter.next();Object key = entry.getKey().toString();Object val = entry.getValue().toString();json.put((String) key, val);}} catch (Exception e) {e.printStackTrace();}return json;}
public static Map<String, String> gettojsontoMap(String json) {Map maps = (Map) JSON.parse(json + "");return maps;}
3通过SharedPreferences将List<String>进行存储
/** * 存储List<String> */ public static void putStrListValue(Context context, String key, List<String> strList) { if (null == strList) { return; } // 保存之前先清理已经存在的数据,保证数据的唯一性 removeStrList(context, key); int size = strList.size(); putIntValue(context, key + "size", size); for (int i = 0; i < size; i++) { putStringValue(context, key + i, strList.get(i)); } } /** * 取出List<String> */ public static List<String> getStrListValue(Context context, String key) { List<String> strList = new ArrayList<String>(); int size = getIntValue(context, key + "size", 0); //Log.d("sp", "" + size); for (int i = 0; i < size; i++) { strList.add(getStringValue(context, key + i, null)); } return strList; }
这篇关于SharedPreferences存储 list map的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!