0

I am parsing a xmlfile on android and I have something similar to:

<images>
 <image></image>
</images>

I have the following code:

Element imagesElement = (Element) poiElement.getElementsByTagName("images").item(0);
                        NodeList images = imagesElement.getElementsByTagName("image");
                        for (int n = 0; n < images.getLength(); n++) {
                            Element imgElement = (Element) images.item(n);
                            String imgUrl = getTagValue("image", imgElement);<< ERROR HERE
                            if (imgUrl != "") {
                                //do something here                             }
                        }

If I run the getTagValue("image",imgElement) when the tag is empty I get a null pointer exception, if I run it when there is something in it it returns the value. I'd expect an empty string if it was empty!

I've tried examining the imgElement in eclipses debugger to try and determine how I check if it's empty but I can't work out how! Can anyone help?

Bex

Bex
  • 4,898
  • 11
  • 50
  • 87

2 Answers2

0

It would appear that Element imgElement = (Element) images.item(n); is returning null. You could encapsulate the code following that statement in an if (imgElement != null) to stop the exception.

As a side note, if you are just reading data from the XML and not changing it, you are better off using the SAXParser rather than the DocumentBuilder class.

techi.services
  • 8,473
  • 4
  • 39
  • 42
  • Thanks for the pointer, but it wasn't imgElement that was null it was it's child node. I will bear in mind the SAXParser though as my app is taking a while to parse at the moment so I need to change it! – Bex May 09 '11 at 08:01
0

I have worked out what I need to do;

Element imgElement = (Element) images.item(n);
NodeList fstNm = imgElement.getChildNodes();  //<--- Get the child nodes of the image element
Node Test = ((Node) fstNm.item(0)); //<---- check that the child node isn't null, 
I don't understand why node, but it works!
Bex
  • 4,898
  • 11
  • 50
  • 87
  • As a shortcut you could try exploring what `String content = imgElement.getTextContent()` did for you. And for further reading [this question](http://stackoverflow.com/questions/5527195/java-dom-gettextcontent-issue) gives quite good insight on handling text content. – harism May 09 '11 at 09:06
  • getTextContent() doesn't exist in the Android SDK as this was the first thing I tried! Thanks for the link though I will have a look! – Bex May 09 '11 at 09:09
  • You're absolutely right, thanks for pointing this out. Actually it exists but only on API level 8 and higher and it's maybe better not to use it. – harism May 09 '11 at 09:16