【问题标题】:Android add ArrayList<Object> as a variable in Class ObjectAndroid 将 ArrayList<Object> 添加为 Class Object 中的变量
【发布时间】:2014-03-18 02:39:48
【问题描述】:

我有两个班级,一个是Question,另一个是Choices。部分字段如下:

Question:

public String id;
public String text;
public String image;
public ArrayList<Choices> choices;


Choices:

boolean isCorrect;
String choice;

简单地说,我得到一些 XML 并解析它。有问题并将可能与问题相关的 3、4 或 5 个答案关联起来,我在所有选择(或答案)中创建了一个 ArrayList&lt;Choices&gt;,然后将 set 放入 Question 类中。但是我尝试读取特定对象中的列表,但它什么也不返回。

这是我进行最终组合和测试的代码:

question.setChoices(choiceList);
//Log.d("demo", ">>>" + question.getChoices());
questionList.add(question);
question = null;
choices = null;
choiceList.clear();

(加长版)

... // other parsing code before this

case XmlPullParser.END_TAG:

            if (parser.getName().equals("question")) {

                // Testing purposes
                //Log.d("demo", ">>>" + choiceList.toString());
                question.setChoices(choiceList);
                //Log.d("demo", ">>>" + question.getChoices());
                questionList.add(question);
                question = null;
                choices = null;
                choiceList.clear();
                Log.d("demo", ">>>" + questionList.get(0).getChoices());

            }

            break;

        default:
            break;

        } // END Switch

        event = parser.next();

    } // END While loop

    return questionList;

}

}

基本上,我查看日志,可以打印Question 对象中除ArrayList&lt;Choices&gt; 信息之外的所有数据。我得到的只是[]。我将不胜感激任何帮助。

编辑的额外信息

else if (parser.getName().equals("choice")) {

                boolean isCorrect;
                String answer;

                if (parser.getAttributeValue(null, "answer") != null) {
                    isCorrect = true;
                    answer = parser.nextText();
                    choices = new Choices(isCorrect, answer);
                }
                else {
                    isCorrect = false;
                    answer = parser.nextText();
                    choices = new Choices(isCorrect, answer);
                }

                choiceList.add(choices);

            } // END Choices Parsing

【问题讨论】:

    标签: java android class arraylist xmlpullparser


    【解决方案1】:

    choicesList.clear 实际上会从列表中删除所有数据。由于列表与问题对象中的列表相同,因此问题对象中的列表也将被清除。与其清除它,不如创建一个新的 ArrayList。

    【讨论】:

    • 我编辑了我的原始帖子。正如你所看到的,我做了选择 = new Choices()。这是你得到的一个很好的启示,现在我正在尝试确定如何实现它。因为整个 while 循环逐行读取 XML。我想我的问题是,我是否需要每次都用一个新的“名字”来做一个新的最少?
    猜你喜欢
    • 2014-05-09
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2014-10-03
    相关资源
    最近更新 更多