Reputation: 163
I have been trying to use Intent method in my program , the code shows no error when I use myactivity.this ... when I use the other two (myactivity.class or this),eclipse shows an error.
Intent i = new Intent(myActivity.this,myActivity2.class);
startActivity(i);
When I use myactivity.class or this in the first param,
Eclipse shows an error of Constructor Intent not defined. Why is that, can anyone explain?
Upvotes: 2
Views: 1859
Reputation: 11324
myActivity.this == Refrence to context
myActivity2.class == Reference to class, this is its class name
this == It is Current Type, say if you are in Thread then it is Thread Type; if you are in Activity then it is Activity Type; if you are in your custom class say CAR then it is CAR type
When you do the this then you get an error because you must not be in main thread in this you can use getApplicationContext()
When you use myActivity.this It Knows that it will be started from this activitie's context.
Upvotes: 10
Reputation: 1136
Maybe you are writing this code in another object ,like in OnClickListener ,thus this is representing the current object of OnClickListener not the MainActivity class. That's why you should use MainActivity.class to reference to main Activity. this in this context is representing the object of OnClickListener.
Upvotes: 0
Reputation: 535
The first param is for the current activities context therefore this or Activity.this or getApplicationContext will do. and the second param refers to the class name where you want to move to. That is why .this in the first param and .class in the second. Hope you got it now.
Upvotes: 0
Reputation: 2970
Let me give you the answer of:
When i use myactivity.class or this in the first param ,Eclipse shows an error of Constructor Intent not defined.
Reason you got error is that you are supposed to pass valid parameters to the Intent Constructor that you are trying to invoke. See this: LINK Which are
And as you mentioned, you tried myactivity.class , refering to KITKAT'S answer this parameter is not valid enough to get passed to the Intent constructor.
As for this is concerned, you shouldn't get any compile error, if you are within valid activity context.
Upvotes: 0