简体   繁体   English

使用自定义对象存储ArrayList

[英]Storing ArrayList with custom object

I'm trying to save ArrayList with a custom object in it. 我正在尝试使用其中的自定义对象保存ArrayList。 Problem is that the ArrayList is in my singleton. 问题是ArrayList在我的单例中。 My singleton "Choices" holds ArrayList<Choice> list; 我的单身人士“ Choices”拥有ArrayList<Choice> list; and the "Choice" has 4 different types of variables. 并且“选择”具有4种不同类型的变量。

I don't know how to access my ArrayList from my activity because the below code didn't work. 我不知道如何从我的活动访问我的ArrayList,因为以下代码不起作用。 getMyList() method returns list. 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();

When I'm retrieving the list I tried something like this but it didn't work. 当我检索列表时,我尝试了类似的方法,但是没有用。

    String json = prefs.getString("list", "");
    Type type = new TypeToken<Choice>() {}.getType();
    ArrayList<Choice> savedList = gson.fromJson(json, type);

Any help or suggestions would help a lot. 任何帮助或建议都会有很大帮助。

How about this while retrieval : 检索时如何处理:

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);
    }

In retrieving code change 检索代码更改
Type type = new TypeToken<Choice>() {}.getType();
to
Type type = new TypeToken<List<Choice>>() {}.getType() ; Type type = new TypeToken<List<Choice>>() {}.getType() ; as you need to parse though a list of your custom object. 因为您需要解析自定义对象的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM