I'm trying to use a button to change from Main Activity on android studio to Main Activity 2 and I get the error
no suitable constructor found for Intent(<anonymous OnClickListener>,Class<MainActivity2>)
Intent intent = new Intent(this, MainActivity2.class);
^
I'm on version 4.1 and I want to assume i'm following an old tutorial or I just missed some punctuation. This is my code:
buttonPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openMainActivity2();
}
public void openMainActivity2(){
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
Just to give more clarity to Caio's answer, when you use this
Intent intent = new Intent(this, MainActivity2.class);
The intent is created in an anonymous inner class ie OnClickListener
. Thus this
does not refer the instance of your Activity (or Context) as intended. You need to provide the correct context of your class.
Hence, do this:
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
you should provide the correct context of your class.
try this:
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
You have to try getApplicationContext()
or activity.this
instead of this
.
I think you are having this issue for " this
". Cause, I can't see any other issue.
Intent intent = new Intent(getApplicationContext(),MainActivity2.class)
startActivity(intent);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.