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!
Something tells me that there’s a problem with
thisoractivityand there’s some code missing here. The code that you’ve put there shouldn’t ever generate a NPE becausethisis never null and if 2 followed 1 immediately,activityshouldn’t be null. It’s possible thatthisisn’t an instance ofActivitybut that would generate a compile error, not an NPE.Edit Ah, I think I see your problem. You need to override
onCreate()and thisActivitywill be instantiated by the Android framework. You then need to move all of the code from the constructor and put it in theonCreate() 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 subclassingActivityfrom yourXmlParserclass and change the constructor to take aContextargument. From there, instantiate theXmlParserin your otherActivity, 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
Activitiescheck out this link. Also, check out this SO post for how to do what you’re trying to do.