1

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");
}
}
naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185
  • I have this: public class XmlParser { private Context context; 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); – SkyeBoniwell Dec 20 '11 at 17:17
  • sorry that formatting looks horrible – SkyeBoniwell Dec 20 '11 at 17:17
  • You could edit your original post to put the code in there. – Heiko Rupp Dec 20 '11 at 17:55

3 Answers3

2

use your Activity name at place of context .

Navdroid
  • 1,541
  • 3
  • 25
  • 52
1

Make sure this statement is inside a non static method.

Rajdeep Dua
  • 11,190
  • 2
  • 32
  • 22
1

The code you posted will not work, as the context is only available within an Activity (or similar) within an Android app. Just calling it via main() will not set the correct context for you (in the above example it is even null and would result in a NPE).

Heiko Rupp
  • 30,426
  • 13
  • 82
  • 119