I'm writing an android apps in Java of Eclipse. I'm not very familiar with the java syntax. I encounter this error.
The constructor Intent(new AdapterView.OnItemClickListener(){},
Class<NoteEditor> ) is undefined
Below is the code
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(this, NoteEditor.class);
startActivity(intent);
}
});
NoteEditor is extends Activity of Android. The above code is correct because I write it in another place it's no error.
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
Intent intent = new Intent(this, NoteEditor.class);
startActivity(intent);
//newGame();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
-
No, the code isn't correct, which is why you're getting a compiler error. this doesn't refer to what you think it does there; it's referring to the anonymous class you're instatiating.Brian Roach– Brian Roach2011年11月15日 05:55:32 +00:00Commented Nov 15, 2011 at 5:55
-
change like this Intent intent = new Intent(YourActivity.this, NoteEditor.class);RajaReddy PolamReddy– RajaReddy PolamReddy2011年11月15日 05:57:15 +00:00Commented Nov 15, 2011 at 5:57
-
post your whole activity code.user370305– user3703052011年11月15日 06:20:46 +00:00Commented Nov 15, 2011 at 6:20
-
write this, Intent intent = new Intent(Category.this, NoteEditor.class);user370305– user3703052011年11月15日 06:27:16 +00:00Commented Nov 15, 2011 at 6:27
3 Answers 3
The context used in your code is wrong, as you're using the anonymous inner class's this. What you should be using is the Activity's context, like so:
Intent intent = new Intent(Category.this, NoteEditor.class);
The first parameter indicates the calling class's context. So you can use the Activity's this or getBaseContext()
public Intent (Context packageContext, Class<?> cls)
Here in your code this refers to your new AdapterView class not a activity,
and for Intent constructor you have to pass a reference of your current activity or application's base context,
replace your code,
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getBaseContext(), NoteEditor.class);
startActivity(intent);
}
});
EDIT: also you can write
Intent intent = new Intent(<your current activity name>.this, NoteEditor.class);
Comments
Your problem is that this applies to the anonymous inner class rather than your Context subclass instance. In general, you'd write YourEnclosingClassName.this to get to that. In your case, you need NodeEditor.this.