In my app I’m parsing an xml, piece of structure doing problems:
<answers>
<answer value="A">A</answer>
<answer value="B">B</answer>
<answer value="C">C</answer>
</answers>
I’m parsing it with XML DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
that works great and depending on answer items I’m creating a RadioButtons like this:
NodeList answers = doc.getElementsByTagName("answers").item(0).getChildNodes();
int j = 0;
RadioGroup group = new RadioGroup(this);
RadioButton button1 = new RadioButton(this);
button1.setId((i+1)*100+(j++));
button1.setText(answers.item(1).getChildNodes().item(0).getNodeValue());
button1.setTextColor(Color.BLACK);
RadioButton button2 = new RadioButton(this);
button2.setId((i+1)*100+(j++));
button2.setText(answers.item(2).getChildNodes().item(0).getNodeValue());
button2.setTextColor(Color.BLACK);
RadioButton button3 = new RadioButton(this);
button3.setId((i+1)*100+(j));
button3.setText(answers.item(3).getChildNodes().item(0).getNodeValue());
button3.setTextColor(Color.BLACK);
This piece of code works perfectly in the emulator, SDK v.7 (Android 2.0), while my HTC Desire runs on Android 2.1u1 (so SDK v.8)
But in the device I get error on this line button2.setText(answers.item(2).getChildNodes().item(0).getNodeValue()); guessing that there is no .item(2) in answers – but it has to be… I was debugging this code within emulator and found out that answers.item(0) is a TextNode containing the name of the XML node “answers”…
But it is true I’m a bit confused and everything is messing up when parsing this XML as I still have to count how deep am I and when to call what index on which element (node)… But still I found this implementation much simpler than using SAX…
Isn’t there something simillar to SimpleXml from PHP in Java???
Anyway, my main problem is: how is it possible that application is working perfectly in emulator while on device it throws NullPointerException on the line where I try to set text for button2???
Many thanks for You help!!!
getChildNodes() returns all
Nodes under answers, not just allElements. You probably want to iterate through all of the children and check if each is anElementwith tag name “answer”How about something like this:
That way you aren’t dependent on a particular number of child elements of answers, and you guarantee you won’t try to access one that doesn’t exist.
If you really want to do it based on the children of an Answers node,