Evgeniy Mishustin
Evgeniy Mishustin

Reputation: 3804

Starting Intent correctly. Difference between this vs MainActivity.this

What is the difference starting new intent from some MainActivity(for example) using:

Intent intent = new Intent(this, SecondActivity.class);

vs

Intent intent = new Intent(MainActivity.this, SecondActivity.class);

Upvotes: 0

Views: 1155

Answers (1)

Er.Rohit Sharma
Er.Rohit Sharma

Reputation: 696

There is not difference in working of intent, but we use these two statements in different situations.

Actually for starting new activity we use intent:

Intent intent = new Intent(Context packageContext, Class<?> cls);

Where on packageContext, we have to pass the context. So that's why we pass 'this' as a context of current activity.

But if we do the same from some anonoymous class like anonymous onClickListener, this refers to the instance of that ananymous class. So in that case we use 'MainActivity.this' which is the context of MainActivity class.

Upvotes: 3

Related Questions