在Android中打开xml文档无法正常工作

时间:2015-07-16 13:53:42

标签: android xml

我在资源/ raw上使用xml文档以填充ListView,这是代码:

List<Item> items = new ArrayList<Item>();
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.data)));
        XmlPullParser p = XmlPullParserFactory.newInstance().newPullParser();
        p.setInput(br);
        int tipoevento = p.next();
        while (tipoevento != XmlPullParser.END_DOCUMENT) {
            switch (tipoevento) {
                case XmlPullParser.START_TAG:
                    items.add(
                            new Item(
                                    Integer.parseInt(p.getAttributeValue(null,"id")),
                                    p.getAttributeValue(null,"name"),
                                    p.getAttributeValue(null,"url")));
                    break;
                default:break;
            }
            tipoevento=p.next();
        }
        br.close();
    }
    catch(Exception e) {
        Log.e("Error: ", e.getMessage());}

而且,当我运行它时,我收到以下错误:Error :: Invalid int:“null”。
列表视图是空的 xml文档不是空的,我做了,这里是:

<?xml version="1.0" encoding="utf-8"?>
<filmList>
<film name="Following" id="R.drawable.following" url="http://www.imdb.com/title/tt0154506/"/>
<film name="Memento" id="R.drawable.memento" url="http://www.imdb.com/title/tt0209144/"/>
<film name="Batman Begins" id="R.drawable.batman_begins" url="http://www.imdb.com/title/tt0372784/"/>
<film name="The Prestige" id="R.drawable.the_prestige" url="http://www.imdb.com/title/tt0482571/"/>
<film name="The Dark Knight" id="R.drawable.the_dark_knight" url="http://www.imdb.com/title/tt0468569/"/>
<film name="Inception" id="R.drawable.inception" url="http://www.imdb.com/title/tt1375666/"/>
<film name="The Dark Knight Rises" id="R.drawable.the_dark_knight_rises" url="http://www.imdb.com/title/tt1345836/"/>
</filmList>

1 个答案:

答案 0 :(得分:1)

您需要检查空值

if (p.getAttributeValue(null,"id") != null) {
    items.add(
      new Item(
            Integer.parseInt(p.getAttributeValue(null,"id")),
                   p.getAttributeValue(null,"name"),
                   p.getAttributeValue(null,"url")));
}