Is there a reason why the ‘this’ keyword only works in my apps main java file onCreate method?
If I try and use ‘this’ anywhere else, I eventually end up with a nullPointerException error.
For example, working version:
public class HelloAndroid extends Activity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
XmlParser xmlParse = new XmlParser();
encounterText = xmlParse.parseXML(this);
}
But if I try and use ‘this’ in separate java class file within my app, I get the NPE.
Thanks
I think what you’re asking (correct me if I’m wrong) is why ‘this’ doesn’t work as an argument for methods that require a reference to the Context. The answer is that this only refers to the Context in classes that extend Activity. Your Activity happens to also be your Context, so this works in those instances. However, when you declare your own class you are no longer within the Activity and so ‘this’ (while it obviously refers to the class you’re in) doesn’t help you get a reference to the Context.
In these situations you need to pass your context in as a reference to your class constructor so that it has access to that object.