开发者

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? Thank开发者_JAVA技巧s


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.


Try XmlPullParser. It's a little bit easier, I think.

XmlPullParser | Android Developers


Try Project|Clean - it might not be getting the raw XML from your resources. Eclipse seems a bit flaky that way, I sometimes change code & it doesn't pick up the changes until its cleaned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜