SkyeBoniwell
SkyeBoniwell

Reputation: 7092

getting the activity for my app

I've been having some issues reading an XML file in my 'res' folder and I think I've narrowed it down to an issue with my apps 'activity'.

I keep getting a NullPointerException on line # 2 below.

Here is my code to get the activity. Is there a better or a right way to do this?

1. Activity activity = this;

2. Resources res = activity.getResources();

3. XmlResourceParser xpp = res.getXml(R.xml.encounters);

Here is the class:

public class XmlParser extends Activity  {


public XmlParser()
    throws XmlPullParserException, IOException
{
    try {
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setValidating(false);

        Activity activity = this;
        Resources res = activity.getResources();
        XmlResourceParser xpp = res.getXml(R.xml.encounters);

    } catch (Exception e) {
        String stackTrace = Log.getStackTraceString(e);
        Log.e("error", stackTrace);
    }
   }
}

And I'm getting the error on the "Resources res = activity.getResources();" line... Thanks!

Upvotes: 0

Views: 70

Answers (2)

Chris Thompson
Chris Thompson

Reputation: 35598

Something tells me that there's a problem with this or activity and there's some code missing here. The code that you've put there shouldn't ever generate a NPE because this is never null and if 2 followed 1 immediately, activity shouldn't be null. It's possible that this isn't an instance of Activity but that would generate a compile error, not an NPE.

Edit Ah, I think I see your problem. You need to override onCreate() and this Activity will be instantiated by the Android framework. You then need to move all of the code from the constructor and put it in the onCreate() method. However, I think this is indicative of a fundamental understanding of how applications work in Android. Instead, what I would do is create a standard Android application in Eclipse. That will create a base activity for you. From there, remove the subclassing Activity from your XmlParser class and change the constructor to take a Context argument. From there, instantiate the XmlParser in your other Activity, the one that was created by Eclipse.

All of that said, I think you should spend some time reading over the application fundamentals in the developer docs to understand how you're supposed to access resources, etc.

Edit 2 For more information about Activities check out this link. Also, check out this SO post for how to do what you're trying to do.

Upvotes: 3

Cata
Cata

Reputation: 11211

If you run that code inside of a Activity class then you could simply do:

Resources res = this.getResources();

XmlResourceParser xpp = res.getXml(R.xml.encounters);

Upvotes: 1

Related Questions