//存json
public void setInfoFromPreference() {
SharedPreferences preferences = getSharedPreferences("json",MODE_PRIVATE);
ArrayList arrayList = new ArrayList();
try {
JSONObject object1 = new JSONObject();
object1.put("contactId", 1);
object1.put("position",1);
JSONObject object2 = new JSONObject();
object2.put("contactId",2);
object2.put("position",2);
JSONObject object3 = new JSONObject();
object3.put("contactId",3);
object3.put("position",3);
arrayList.add(object1);
arrayList.add(object2);
arrayList.add(object3);
} catch (JSONException e) {
e.printStackTrace();
}
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
Log.d(TAG, "onCreate: json = " + json);
editor.putString("icon", json);
editor.commit();
}
//取json
public void getInfoFromPreference() {
SharedPreferences preferences = getSharedPreferences("json", MODE_PRIVATE);
String json = preferences.getString("icon",null);
Log.d(TAG, "getInfoFromPreference: json = " + json);
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<HomeIconBean>>(){}.getType();
ArrayList<HomeIconBean> arrayList = gson.fromJson(json, type);
for (int i = 0; i < arrayList.size(); i++) {
Log.d(TAG, "getInfoFromPreference: arrayList = " + arrayList.get(i).getContactId());
Log.d(TAG, "getInfoFromPreference: arrayList = " + arrayList.get(i).getPosition());
}
}