[英]Storing ArrayList with custom object
我正在嘗試使用其中的自定義對象保存ArrayList。 問題是ArrayList在我的單例中。 我的單身人士“ Choices”擁有ArrayList<Choice> list;
並且“選擇”具有4種不同類型的變量。
我不知道如何從我的活動訪問我的ArrayList,因為以下代碼不起作用。 getMyList()
方法返回列表。
SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(Choices.getInstance().getMyList());
editor.putString("list", json);
editor.commit();
當我檢索列表時,我嘗試了類似的方法,但是沒有用。
String json = prefs.getString("list", "");
Type type = new TypeToken<Choice>() {}.getType();
ArrayList<Choice> savedList = gson.fromJson(json, type);
任何幫助或建議都會有很大幫助。
檢索時如何處理:
String json = prefs.getString("list", "");
ArrayList<Choice> savedList = (ArrayList<Choice>) jsonToList(json,
new TypeToken<ArrayList<Choice>>() {
}.getType());
public static Object jsonToList(String jsonString, Type type) {
return new Gson().fromJson(jsonString, type);
}
檢索代碼更改
Type type = new TypeToken<Choice>() {}.getType();
至
Type type = new TypeToken<List<Choice>>() {}.getType()
; 因為您需要解析自定義對象的列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.