码迷,mamicode.com
首页 > 移动开发 > 详细

android 使用SharedPreferences保存list数据

时间:2015-08-14 11:54:20      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:android   sharedpreferences   list数据   java   

List<Map<String, String>> list = new ArrayList<Map<String, String>>();
List<Map<String, String>> test = getInfo(this, "name");


for (int i = 0; i < test.size(); i++) {
Map<String, String> itemMap = test.get(i);
Iterator<Entry<String, String>> iterator = itemMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry<String, String> entry = iterator.next();
if (!entry.getValue().equals(r.cashierNumber)) {
itemMap.put(entry.getKey(), entry.getValue());
}
}
itemMap.put(“test”, “test”);
list.add(itemMap);
saveInfo(this, "name", list);


}


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 {
System.out.println(entry.getKey() + ":" + entry.getValue());
object.put(entry.getKey(), entry.getValue());
} catch (JSONException e) {


}
}
mJsonArray.put(object);
}


SharedPreferences sp = context.getSharedPreferences("listname",
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("listname",
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;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

android 使用SharedPreferences保存list数据

标签:android   sharedpreferences   list数据   java   

原文地址:http://blog.csdn.net/cxt528440900/article/details/47657751

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!