Is there any difference between Activityname.this()
& this
in Android?
I am trying to open an activity from same activity with button in dialog box? I am using getApplicationContext()
in intent. In some mobiles it works, but in others it force closes?
Between ActivityName.this and this which one I should use & why?
no
MyActivity.this
is the same thing as just usingthis
when you are in the activity itself and not something like a runnable wherethis
would refer to the runnable and not the contextyou should always use
this
orgetActivity()
if in a fragment and never usegetApplicationContext()
check here for why you shouldn't use
getApplicationContext()
getApplication() vs. getApplicationContext()
This depends on where you are calling it from. If you are inside the
Activity
, not inside of a listener or inner class like inonCreate
then no. They both refer to theActivity context
.If you are say inside of an
onClickListener
then yes.this
refers to thelistener
and you need to useActivityName.this
or something likeThis will be the same as when using a
Dialog
orAlertDialog
, you will want to useActivityName.this
This is an answer that talks about the difference of
Context
s but there's a better one I will see if I can findA great Context explanation
Edit for more completeness
AFAIK,
getApplicationContext()
orActivityName.this
is fine forToasts
. The example in the docs usesgetApplicationContext()
. But the Toast Docs saysSo there may be certain instances where one is better but I have always used
Activity Context
and I guess I will until I am corrected on this.