I know this is a basic question but i have seen that using the method getApplicationContext() to get the context work at places where the "this" keyword does't work, especially inside an onClickListener. Why is this?
Asked
Active
Viewed 245 times
-2
-
3Possible duplicate of [Difference between getContext() , getApplicationContext() , getBaseContext() and "this"](http://stackoverflow.com/questions/10641144/difference-between-getcontext-getapplicationcontext-getbasecontext-and) – Mithun Sarker Shuvro Jun 05 '16 at 19:06
2 Answers
1
In the case of an OnClickListener, this
is the anonymous class of the OnClickListener, therefore not a Context.
Whereas calling that method works because it's from the Activity class.
Alternatively, MyActivity.this
works as well.

OneCricketeer
- 179,855
- 19
- 132
- 245
1
getActivity()
: Used inside a Fragment
to get the context of activity it is currently associated to.
this
: Returns the context of current block in which it is called. If it is called inside an onClickListener
then it would return the context of that listener, not the activity.
MyActivity.this
: Returns the context of the activity. This can be used at the place of getActivity()
as an alternate. (MyActivity should be read as the activity name you are using).

Rohit5k2
- 17,948
- 8
- 45
- 57