3

I have looked at a lot of android tutorials over the internet. In these tutorials they use the this context for the context everywhere. I know what this keyword means in Java, but I can't make equal this, with the this keyword in Android programming. For example, at AlertDialog.Builder, on the developer.android.com site, there is only one reference at the parameters to the Context, but I can't learn what this this means here.

Malik Daud Ahmad Khokhar
  • 13,470
  • 24
  • 79
  • 81
Zwiebel
  • 1,605
  • 4
  • 21
  • 37
  • take a look a this post, it could help you to understand. http://stackoverflow.com/questions/3572463/what-is-context-in-android – JAiro Jun 29 '11 at 12:57
  • 2
    The only thing that came to mind when I saw this question was "What is the meaning of this!" – mark-cs Jun 29 '11 at 13:01

6 Answers6

12

if you have an Activity you can use this because:

  • this is the current instance of a class
  • an Activity is inherits from the class "Context"

so you can use your current Activity as a Context.

Look here for the Acitivty doc

and here for an explanation of this

Emzor
  • 1,380
  • 17
  • 28
Fender
  • 3,055
  • 1
  • 17
  • 25
0

If you know "this" variable.. then u may also know that it holds reference for the current object.. so if some method asks for a Context object you can pass this variable only when it extends classes like Context or Activity.. Because Activity implements context so obeviously its a Context

ngesh
  • 13,398
  • 4
  • 44
  • 60
0

Context of current class is called This in Android.

DynamicMind
  • 4,240
  • 1
  • 26
  • 43
0

Here is another question where they explain Context. As activities and services extend Context, the this context is a reference to this activity or service.

Community
  • 1
  • 1
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
0

The keyword this is simply a reference -- within an instance of a class -- to itself.

There are two common uses of "this" in Android. These aren't particular to Android, but are valid in Java in general.

  1. this.getResources() says to call the getResources() method on this instance. The this portion of it is usually unnecessary and used implicitly.

  2. Foo.this.getResources() could be called from an inner class. This could be handy if the inner class defines getResources() also, but you want the version defined in the other class.

Zack Marrapese
  • 12,072
  • 9
  • 51
  • 69
0

this is a reference to the current object

You can use this to refer to any current instance and any instance of its super class.

If your class extends Activity. It is a case of inheritance. your class is subclass and Activity class is parent class. then you can use this keyword to get instance of Activity beacause Activity class is super class of your class. This is implicit casting

also Activity class Context as superclass. so you can refer the instance of that class using this keyword.

Thanks

Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243