Thursday, April 26, 2012

getElementsByTagName returns null in Android 4.0 or 3.0

Today, my application crashed on Android 4 device. I always thought it will work on Android 4 because it was a simple application but I guessed wrong.

For some reason  getElementsByTagName  returns null in Android 4.0 or Android 3.0, if your  code look somewhat like this.

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();
 InputSource is = new InputSource(new StringReader("Some XML here and there"));
 Document document = builder.parse(is);
 Element root = document.getDocumentElement();
 NodeList items = root.getElementsByTagName("tag");  <-- this function will always return null on Android 4 

When i dig in I found a bug reported in Google forums. I found this very hard to believe because this is a very primary level issue and how did it get passed?

Anyway, As a work around I had to use XPath. Just remember to change the project's Android SDK to 2.2 or higher otherwise XPath classes are not visible. They resides in javax.xml.xpath namespace. Or you can use XmlPullParser which reads documents from top to bottom.

InputSource is = new InputSource(new StringReader("Some XML here and there"));
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
NodeList nodeList = (NodeList) xPath.evaluate("/xpath", is, XPathConstants.NODESET);