我想使用jsonarray将arraylist存储到sharedpreferences中。很可能我成功地存储了它,但当我检索JSON
数组时,应用程序停止。
代码存储arraylist
中的sharedpreferences
:
ArrayList<HashMap<String, String>> cart = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_PID, pid);
map.put(TAG_NAME, name);
map.put(TAG_CATEGORY, category);
map.put(TAG_PRICE, price);
map.put(TAG_IMAGE,String.valueOf(resId));
cart.add(map);
JSONArray result = new JSONArray(cart);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("CART", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("item", result.toString());
editor.commit();
Intent a = new Intent("com.example.pb.VIEWCART");
startActivity(a);
检索arraylist
的代码:
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("CART", 0);
String storedCollection = sharedPreferences.getString("item", null);
ArrayList<HashMap<String, String>> collection = new ArrayList<HashMap<String, String>>();
try {
JSONArray array = new JSONArray(storedCollection);
HashMap<String, String> item = null;
for (int i =0; i<array.length(); i++) {
Log.i("CHECKPOINT","into loop" );
String obj = (String) array.get(i);
JSONObject ary = new JSONObject(obj);
Iterator<String> it = ary.keys();
item = new HashMap<String, String>();
while(it.hasNext()) {
String key = it.next();
item.put(key, (String)ary.get(key));
}
collection.add(item);
}
} catch (JSONException e) {
Log.e("TAG", "while parsing", e);
}