choicesList.clear will actually delete all data from the list. Since the list is the same one as in the question object, the one in the question object gets cleared too. Instead of clearing it, you want to create a new ArrayList.
Android add ArrayList<Object> as a variable in Class Object
-
16-06-2023 - |
Question
I have two classes, one is a Question
and the other Choices
. Some fields are as follows:
Question
:
public String id;
public String text;
public String image;
public ArrayList<Choices> choices;
Choices
:
boolean isCorrect;
String choice;
Put simply, I get some XML and parse it. There are Questions and to associate the 3, 4, or 5 answers that may be with a questions, I make an ArrayList<Choices>
of all choices (or answers) and then set
it into the Question class. But I try to read the list in a particular object, and it returns nothing.
Here's the code where I do the final combinations and testing:
question.setChoices(choiceList);
//Log.d("demo", ">>>" + question.getChoices());
questionList.add(question);
question = null;
choices = null;
choiceList.clear();
(LONGER VERSION)
... // 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;
}
}
Basically, I look at the log and I can print all data in the Question
object except for the ArrayList<Choices>
information. All I get is []
. I'd greatly appreciate any help with this.
EDITED EXTRA INFO
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
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow