[Android]用SharedPreferences儲存List(Map(String, String))資料
原因:
SharedPreferences沒有儲存數組的方法,但是有時候為了儲存一個數組而進行序列化,或者動用sqlite都是有點殺豬焉用牛刀的感覺,所以就自己動手改進一下吧。
解決方案:採用的方式是先轉換成JSON,然後儲存字串,取出的時候再講JSON轉換成數組就好了。
public void saveInfo(Context context, String key, List> datas) {JSONArray mJsonArray = new JSONArray();for (int i = 0; i < datas.size(); i++) {Map itemMap = datas.get(i);Iterator> iterator = itemMap.entrySet().iterator();JSONObject object = new JSONObject();while (iterator.hasNext()) {Entry 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> getInfo(Context context, String key) {List> datas = new ArrayList>();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 itemMap = new HashMap();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;}