-1

I got stuck with an error while writing this part of code:

ListView lv = (ListView) this.findViewById(R.id.toDoListView);
    lv.setAdapter(tdla);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent newIntent = new Intent(this, DisplayMessageActivity.class);//<--- Cannot resolve constructor
            newIntent.putExtra(EXTRA_MESSAGE, "TETTE");
            startActivity(newIntent);
        }
    });

I thought Intent constructor should be the same as declaring it in a simple function linked to a Button as:

public void sendMessage(View view){
    Intent newIntent = new Intent(this, DisplayMessageActivity.class);//<--- OK
    ...sth...
    startActivity(newIntent);
}

Also How to handle the click event in Listview in android? shows a similar example but I can't figure out what I'm missing.

Community
  • 1
  • 1
Andrea Grimandi
  • 631
  • 2
  • 8
  • 32

4 Answers4

3

Change

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent newIntent = new Intent(this, DisplayMessageActivity.class);//<--- Cannot resolve constructor

    }
});

to for activity

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent newIntent = new Intent(getApplicationContext(), DisplayMessageActivity.class);
    }
});

and for fragment

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent newIntent = new Intent(getActivity(), DisplayMessageActivity.class);
    }
});
eddykordo
  • 607
  • 5
  • 14
1

replace "this"

Intent newIntent = new Intent(yourActivity.this, DisplayMessageActivity.class);

or for fragment

Intent newIntent = new Intent(getActivity(), DisplayMessageActivity.class);
Ravi
  • 34,851
  • 21
  • 122
  • 183
1

Change your intent :

Intent newIntent = new Intent(this, DisplayMessageActivity.class);

to this :

Intent newIntent = new Intent(YourActivity.this, DisplayMessageActivity.class);

Don't use "this" keyword with intent when you are using intent inside any click listener.

SANAT
  • 8,489
  • 55
  • 66
1

You are inside the Itemclick listener, which has no context (no Activity).

Intent newIntent = new Intent(YourActivity.this, DisplayMessageActivity.class)
Roel Strolenberg
  • 2,922
  • 1
  • 15
  • 29