Java/Android xml parsing causes NullPointerException

I have a problem with parsing XML file on android.

My examples.xml file look like this:

<categories>
    <example>something</example>
</categories>

And my Java code:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(getResources().openRawResource(R.xml.examples));
doc.getDocumentElement().normalize(); //here it throws NullPointerException

It throws a NullPointerException when I try to normalize().

I am inspired by this simple tutorial http://sanjaal.com/java/tag/getdocumentelementnormalize/

Can anyone tell me what I’m doing wrong? Thanks

Answer

Try moving your xml file to the res/raw folder, then try this:

Document doc = db.parse(getResources().openRawResource(R.raw.examples));

Let me know if that works.

EDIT: if you look at http://developer.android.com/reference/android/content/res/Resources.html#openRawResource%28int%29 it basically says you can only use that on drawable, sound and raw resources.

Leave a Reply

Your email address will not be published. Required fields are marked *