views:

46

answers:

1

So I'm writing an android app, and I have an xml parser class that parses my xml files and builds me a tree

I want to reuse my xml parser code for different xml files

However, having problems with getXml(resourceID) not working:

public class myactivity extends Activity {

  public void someMethod()  {

    Xmlparser myparser = new Xmlparser();
    myparser.parseXML(this.context, R.xml.somedata);

  }

  public void someOtherMethod(){

    Xmlparser adifferentparser = new Xmlparser();
    adifferentparser.parseXML(this.context, R.xml.differentdata);

  }

}

public class Xmlparser{

import java.io.IOException;
import java.util.Vector;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;

private XmlResourceParser xrp;

  public String parseXML(Context cont, int resourceID){
    xrp = cont.getResources().getXml(resourceID);
  //xrp = cont.getResources().getXml(R.xml.differentdata); // this works, but isn't any good for code reuse!
  }

}

When I hard code it with a resource ID, it works (e.g. getXml(R.xml.differentdata)), but not when I pass a resource ID as an int to the method in the class where I know what xml file I want to use (as in the code snippet above)

I could create the XmlResourceParser object in the activity class, get the xml file and then pass that XmlResourceParser object into my Xmlparser but that'd be solving the wrong problem, which is how to pass a resource ID

A: 

Hi try this wayout

public class XMLParser {
    private Resources _resources;

    public XMLParser(Resources resources){
        this._resources = resources;
    }

    public void parse(int resID) {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            SAXParser parser = factory.newSAXParser();
            CardListHandler handler = new CardListHandler();
            parser.parse(this._resources.openRawResource(resID), handler);


        } catch (Exception e) {
            throw new RuntimeException(e);
        } 
    }

}
Praveenb
Yes, only this means I have change my code to use SAX parser, which I'd rather not do
Spoon Thumb