Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlPullParser get file from filesystem

I my app creater xml file in Android file system. I ned parse this file with XmlPullParser, but I get error wile compilation: "variable parser might not have been initialized". My code:

InputStream inputStream = openFileInput("settings.xml");
XmlPullParser parser;
parser.setInput(inputStream, null);

Have no idea, how to repair it. I use Intellij IDEA12 and Android 2.3 SDK.

like image 742
Coma White Avatar asked Jun 11 '26 10:06

Coma White


2 Answers

I use Eclipse and the below code has worked for me:

You might be missing the below first line:

 XmlPullParserFactory xppf = XmlPullParserFactory.newInstance();
 xppf.setNamespaceAware(true); 
 XmlPullParser xpp = xppf.newPullParser();

 File myXML = new File("myXML.xml"); // give proper path            
 FileInputStream fis = new FileInputStream(myXML);

 xpp.setInput(fis, null);
like image 197
SKK Avatar answered Jun 13 '26 00:06

SKK


Its working code in eclipes but dont know about Intellij IDEA12

write this code to open and get xml from assets or modify according to your need

try {           

    XmlPullParserFactory     xppf = XmlPullParserFactory.newInstance();
    XmlPullParser  = xppf.newPullParser();                  
    AssetManager manager = context.getResources().getAssets();
    InputStream input = manager.open("createDb.xml");
    xpp.setInput(input, null);
    int type = xpp.getEventType();
    while(type != XmlPullParser.END_DOCUMENT) {
        if(type == XmlPullParser.START_DOCUMENT) {

            Log.d(Tag, "In start document");
        }
        else if(type == XmlPullParser.START_TAG) {
            Log.d(Tag, "In start tag = "+xpp.getName());
        }
        else if(type == XmlPullParser.END_TAG) {
            Log.d(Tag, "In end tag = "+xpp.getName());

        }
        else if(type == XmlPullParser.TEXT) {
            Log.d(Tag, "Have text = "+xpp.getText());
            if(xpp.isWhitespace())
            {

            }
            else
            {
                String strquery = xpp.getText();
                db.execSQL(strquery);
            }

        }
        type = xpp.next();
    }
} 
catch (XmlPullParserException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
like image 45
Monty Avatar answered Jun 13 '26 02:06

Monty