1

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

Dan S
  • 9,139
  • 3
  • 37
  • 48
SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185

3 Answers3

1

'this' refers to the instance of the class. It is not something specific to onCreate method

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

Every class instance will have respective 'this' reference. 'this' really means instance of the class you declared in, in your example HelloAndroid instance. In your example you are using same class as parse handler that is why it is working, in another class you might have DefaultHandler defined.

kosa
  • 65,990
  • 13
  • 130
  • 167
1

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.

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236