开发者

How to start second activity in android? getting error

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 cons开发者_运维百科tructor Intent(new View.OnClickListener(){}, Class<AuswahlActivity>) is undefined

How do I get this working?


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.


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


Did you also write the activity in the manifest file?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜