Home » Android » How to start second activity in android? getting error

How to start second activity in android? getting error

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have two java files. In the first I have my activity which starts when the app starts.
The second is called “AuswahlActivity.java” and the xml file “auswahl.xml”. I have this code into AuswahlActivity.java:

 public class AuswahlActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.auswahl);
        //Your code here
    }
}

Now I want to start the activity like this:

Intent myIntent = new Intent(this, AuswahlActivity.class);
this.startActivity(myIntent);

But I get the error message The constructor Intent(new View.OnClickListener(){}, Class<AuswahlActivity>) is undefined

How do I get this working?

How to&Answers:
Intent myIntent = new Intent(this, AuswahlActivity.class);    
this.startActivity(myIntent); 

This part of your code is possible located inside a OnClickListener, Just use

Intent myIntent = new Intent(YouCurrentActivity.this, AuswahlActivity.class);
YouCurrentActivity.this.startActivity(myIntent); 

The reason is, within an Anonymous Class (your OnClickListener) this refers to the Onclicklistener and not the activity…The first param for Intent is the Context (which should be the activity), hence the error.

Answer:

I assume you try to start your new activity inside an OnClickListener. That’s why this refers to the OnClickListener on not to the Activity. And that’s why an appropriate constructor can’t be found.

So you should use

Intent myIntent = new Intent(TheCurrentActivity.this, AuswahlActivity.class);

instead

Answer:

Did you also write the activity in the manifest file?

Answer:

My guess is that the line:

Intent myIntent = new Intent(this, AuswahlActivity.class);

occurs in an OnClickListener that is an anonymous inner class of your primary Activity. Just prefix this with the class name of the activity.

Answer:

Use it this way

Intent myIntent = new Intent(CallerActivity.this, AuswahlActivity.class);
CallerActivity.this.startActivity(myIntent);

Where CallerActivity is the name of your first activity. Android is throwing that error becaise you may be calling it from some inner class.