for (int i = 0; i < nodeList.getLength(); i++) {
Element e = (Element) nodeList.item(i);
event.setName(parser.getValue(e, NODE_NAME));
event.setDate(parser.getValue(e, NODE_DATE));
event.setLocation(parser.getValue(e, NODE_LOC));
Log.d("Thisworks!:", event.getName());
eventsList.addLast(event);
}
for (Event curevent : eventsList) {
Log.d("ThisDoesnt!?:", curevent.getName());
}
Output should be:
name1
name1
name1
name2
name2
name3
name3
Thisworks! outputs different values every time, as expected.
But when i loop through the list and output, it only outputs:
name3
name3
name3
name3
name3
name3
name3
Am i missing something completely obvious here?
You should be adding a new Event
to the eventsList
each time through the loop, not setting the values of the same event
.
eventsList.addLast(event)
does not make a copy, it just adds a reference to event
to the list. So there is only ever one event
object, which you keep overwriting.
You're forgetting to create a new Event object in your loop. What's happening is that the same Event object keeps getting updated. Try this:
for (int i = 0; i < nodeList.getLength(); i++) {
Element e = (Element) nodeList.item(i);
Event event = new Event(); // You're missing this.
event.setName(parser.getValue(e, NODE_NAME));
event.setDate(parser.getValue(e, NODE_DATE));
event.setLocation(parser.getValue(e, NODE_LOC));
Log.d("Thisworks!:", event.getName());
eventsList.addLast(event);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.