XmlPullParserException while parsing a resource file in Android
Asked Answered
M

1

5

I'm trying to parse an XML file that I have in my resources folder. This is what I'm trying to do -

public void loadXMLtoDB() {

    Resources resource = mContext.getResources();
    dbInstance = new DBProvider();
    dbInstance.onCreate();
    try{
        XmlResourceParser parser = resource.getXml(R.xml.default_apps); 

        parser.nextTag();
        readApps(parser);

    } catch (Exception e) {
        e.printStackTrace();
    }
}....

private void readApps(XmlResourceParser parser) throws XmlPullParserException, IOException {

    parser.require(XmlPullParser.START_TAG, null, "appsList");

    while(parser.next() != XmlPullParser.END_TAG){
        if(parser.getEventType() != XmlPullParser.START_TAG)
            continue;

        String name = parser.getName();

        if(name.equals("appIcon")){
            readAppIcon(parser);
        }
        else 
            skip(parser);
    }
} .....

This is my XML file -

<appsList xmlns:launcher="http://schemas.android.com/apk/res/com.example.kids" >
    <appIcon>
        <className>com.sec.android.app.camera.Camera</className>
        <iconPosition>0</iconPosition>
        <packageName>com.sec.android.app.camera</packageName>
        <screen>0</screen>
    </appIcon>
    <appIcon>
        <className>com.sec.android.gallery3d.app.Gallery</className>
        <iconPosition>1</iconPosition>
        <packageName>com.sec.android.gallery3d</packageName>
        <screen>0</screen>
    </appIcon>
</appsList>

and this is the exception I am getting :
org.xmlpull.v1.XmlPullParserException: Binary XML file line #-1: expected start or end tag (position:Binary XML file line #-1)

As far as I know, the XML is alright - yet there is a XMLParsing exception.

Manna answered 13/11, 2013 at 13:50 Comment(0)
M
13

This is what was wrong -

  1. parser.nextTag(); should be replaced by parser.next();
  2. As this is an XML file in res/xml folder, we get a XmlResourceParser rather than a InputStream when opening the file. Besides, when we do setInput() for an XmlPullParser the parser is advanced to the next high level token (START_DOCUMENT to be precise). Hence, we need to do parser.next() twice as opposed to only once and only then will parser.require(XmlPullParser.START_TAG, null, "appsList") be correct.
Manna answered 1/12, 2013 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.