0

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);
Evgeniy Mishustin
  • 3,343
  • 3
  • 42
  • 81
  • 5
    this is refereed to as current context of your activity.But when you implement the button click listener you go to the anonymous class where the scope of this is not available so you write that Activity name with this keyword. – Sagar Gangawane Sep 20 '16 at 09:15
  • Seems the OP needs to read more on what a context is! (this) is known to confuse many developers! – Eenvincible Sep 20 '16 at 09:17
  • http://stackoverflow.com/questions/22966601/what-is-different-between-mainactivity-this-vs-getapplicationcontext – IntelliJ Amiya Sep 20 '16 at 09:17
  • almost the same but the context matters from where you are trying to use it, for head start, you are trying to access current class object but you can't use the object of anonymous class to do what you are trying to do so now you can explore more – Pavneet_Singh Sep 20 '16 at 09:23

1 Answers1

3

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.

Er.Rohit Sharma
  • 696
  • 5
  • 21