原因:
SharedPreferences没有保存数组的方法,但是有时候为了保存一个数组而进行序列化,或者动用sqlite都是有点杀猪焉用牛刀的感觉,所以就自己动手改进一下吧。
解决方案:
采用的方式是先转换成JSON,然后保存字符串,取出的时候再讲JSON转换成数组就好了。
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) { } } mJsonArray.put(object); } SharedPreferences sp = context.getSharedPreferences("finals", Context.MODE_PRIVATE); Editor editor = sp.edit(); editor.putString(key, mJsonArray.toString()); editor.commit(); } 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) { } return datas; }