8

In the earlier Android Programming Tutorial, page 192, we see an implementation of LunchList#onOptionsItemSelected. Within this implementation we see two Intents passed to startActivity: one whose constructor is passed LunchList.this, the other whose constructor is passed this.

What's the difference?

See lines 78 - 91 here. Note how onOptionsItemSelected is not declared within an inner class.

In Android/Java does the value of this change within the context of event handlers or function binding via reflection? Could both Intent instances be passed this?

ybakos
  • 8,152
  • 7
  • 46
  • 74

3 Answers3

11

In Java, this refers to the containing class, and ClassName.this refers to the first containing class whose name is ClassName. Event handlers are typically written as anonymous, inner classes, so if you want to refer to the event handler's containing class (and not the event handler's class), you need to specify ContainingClass.this, not this.

Reference: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.4

JimN
  • 3,120
  • 22
  • 35
3

When you are creating an Intent inside an Inner Class use ClassName.this(here className must be the Activity class Name) and if creating Intent inside an Activity class you can use this.

Nishant
  • 32,082
  • 5
  • 39
  • 53
  • I've added a link to the source in question. Note that `onOptionsItemSelected` is not declared within an inner class – ybakos Sep 26 '12 at 04:04
  • You can also use `this` in place of `LunchList.this`. – Nishant Sep 26 '12 at 04:08
  • Meaning, there is no difference in this case? – ybakos Sep 26 '12 at 04:17
  • Yes,because you are creating the `Intent` inside the top level class – Nishant Sep 26 '12 at 04:22
  • That's what I thought, but I've been hacking around with a "sketch" trying to see about using the reflection API... but I do realize that in Java, this always means "the instance itself." Now my question is, why was it written this way? There are other examples in the text that use ClassName.this within non-inner class methods. Hm. – ybakos Sep 26 '12 at 04:24
  • 1
    Why was it written this way? Possibly the code was in an inner class where the `ClassName.this` was necessary, and then later refactored to be in the top-level class itself. – JimN Sep 26 '12 at 04:37
1

For this example it will make no difference as in either condition the class that will start the activity will remain same. First parameter of the Intent refers to the context of the class from where the activity will be launched and from where the bundle data will be passed.

Calvin
  • 617
  • 1
  • 12
  • 34