Last entered HashMap key is setting for every element in the map



I'm using XMLPullParser to parse my XML into a hashmap. My XML is a "menu" and the hashmap's key is the category and the value is an ArrayList of menu items. But, in the HashMap, the last key entered is the key for ALL of the items in the HashMap, not just the last element. Why is this? Here is my code:



public HashMap<String, ArrayList<String>> getMenu() throws IOException,
XmlPullParserException {

XmlPullParser xpp = appContext.getResources().getXml(R.xml.menu);

HashMap<String, ArrayList<String>> menuItems = new HashMap<String, ArrayList<String>>();
ArrayList<String> items = new ArrayList<String>();
String catName = null;
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (xpp.getName().equals("categoryname")) {
catName = xpp.nextText();
menuItems = new HashMap<String, ArrayList<String>>();
} else if (xpp.getName().equals("item")) {
items.add(xpp.nextText());
}
} else if (xpp.getEventType() == XmlPullParser.END_TAG) {
if (xpp.getName().equals("category")) {
System.out.println("Adding Category: " + catName);
menuItems.put(catName, items);
catName = new String();
}
}

xpp.next();
}

for (Map.Entry<String, ArrayList<String>> entry : menuItems.entrySet()) {
String key = entry.getKey();
ArrayList<String> value = entry.getValue();
for(String str : value) {
System.out.println("Category: " + key + " Item: " + str);
}
}

return menuItems;
}


and the XML I am parsing looks like this:



<?xml version="1.0" encoding="UTF-8"?>
<restaurant>
<restaurantname>Arbys</restaurantname>
<category>
<categoryname>Roast Beef Sanwiches</categoryname>
<item>Sandwich</item>
<item>Melt</item>
</category>
<category>
<categoryname>Beverages</categoryname>
<item>Brewed Iced Tea</item>
</category>
<category>
<categoryname>Breakfast</categoryname>
<item>Bacon, Egg &amp; Cheese Biscuit</item>
<item>Chicken Biscuit</item>
</category>
<category>
<categoryname>Chicken</categoryname>
<item>Crispy Chicken Sandwich</item>
<item>Prime-Cut Chicken Tenders</item>
</category>
</restaurant>


and my log looks like this:



System.out(6523): Category: Chicken Item: Sandwich
System.out(6523): Category: Chicken Item: Melt
System.out(6523): Category: Chicken Item: Brewed Iced Tea
System.out(6523): Category: Chicken Item: Bacon, Egg & Cheese Biscuit
System.out(6523): Category: Chicken Item: Chicken Biscuit
System.out(6523): Category: Chicken Item: Crispy Chicken Sandwich
System.out(6523): Category: Chicken Item: Prime-Cut Chicken Tenders


So, 'Chicken' is the category for them all, however, it should only be the category for the last 2 items. Anyone know what's up? Thanks


No comments:

Post a Comment