I’m trying to use getResources().getXml so that I can access an XML file in my ‘res’ folder. Apparently from what I’ve read, I need something like this:
XmlPullParser xpp = context.getResources().getXml(R.xml.encounters);
So I put that in, and I also imported “android.content.Context”
But I keep getting an error on ‘context’ that says:Cannot make a static reference to the non-static field context
Is there a way to fix this?
Here is my whole code:
package t.HelloAndroid;
import java.io.IOException;
import java.io.StringReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.res.XmlResourceParser;
import android.content.Context;
import android.app.Activity;
public class XmlParser {
public static void main (String args[])
throws XmlPullParserException, IOException
{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
//XmlResourceParser xrp = context.getResources().getXml(R.xml.encounters);
XmlPullParser xpp = context.getResources().getXml(R.xml.encounters);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+xpp.getName());
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Text "+xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");
}
}
The code you posted will not work, as the
contextis only available within an Activity (or similar) within an Android app. Just calling it viamain()will not set the correct context for you (in the above example it is evennulland would result in a NPE).