How to handle the click event in Listview in android?

AndroidListviewAndroid IntentOnitemclicklistenerOnitemclick

Android Problem Overview


The below is my testing code to create the list view, the list view display successfully, however, there is error in click event. I would like to create an intent to send a hardcode message to an new activity. However, it show error for the line

Intent intent = new Intent(context, SendMessage.class);

So , the problem is , what should I provide for this class?

Also , instead of hard code the output message, how to capture the data in list view row and pass to the new activity? e.g. BBB,AAA,R.drawable.tab1_hdpi for the first row.

Thanks.

public class MainActivity extends Activity {
	public final static String EXTRA_MESSAGE = "com.example.ListViewTest.MESSAGE";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ArrayList<ListEntry> members = new ArrayList<ListEntry>(); 
		members.add(new ListEntry("BBB","AAA",R.drawable.tab1_hdpi));
		members.add(new ListEntry("ccc","ddd",R.drawable.tab2_hdpi));
		members.add(new ListEntry("assa","cxv",R.drawable.tab3_hdpi));
		members.add(new ListEntry("BcxsadvBB","AcxdxvAA"));
		members.add(new ListEntry("BcxvadsBB","AcxzvAA"));
		members.add(new ListEntry("BcxvBB","AcxvAA"));
		members.add(new ListEntry("BvBB","AcxsvAA"));
		members.add(new ListEntry("BcxvBB","AcxsvzAA"));
		members.add(new ListEntry("Bcxadv","AcsxvAA"));
		members.add(new ListEntry("BcxcxB","AcxsvAA"));
		ListView lv = (ListView)findViewById(R.id.listView1);
		Log.i("testTag","before start adapter");
		StringArrayAdapter ad = new StringArrayAdapter (members,this);
		Log.i("testTag","after start adapter");
		Log.i("testTag","set adapter");
		lv.setAdapter(ad);
		lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
            	Intent intent = new Intent(context, SendMessage.class);
            	String message = "abc";
            	intent.putExtra(EXTRA_MESSAGE, message);
                startActivity(intent);
            }
        });
	}

Android Solutions


Solution 1 - Android

I can not see where do you declare context. For the purpose of the intent creation you can use MainActivity.this

 lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                Intent intent = new Intent(MainActivity.this, SendMessage.class);
                String message = "abc";
                intent.putExtra(EXTRA_MESSAGE, message);
                startActivity(intent);
            }
        });

To retrieve the object upon you have clicked you can use the AdapterView:

ListEntry entry = (ListEntry) parent.getItemAtPosition(position);

Solution 2 - Android

ListView has the Item click listener callback. You should set the onItemClickListener in the ListView. Callback contains AdapterView and position as parameter. Which can give you the ListEntry.

lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
                Intent intent = new Intent(MainActivity.this, SendMessage.class);
                String message = entry.getMessage();
                intent.putExtra(EXTRA_MESSAGE, message);
                startActivity(intent);
            }
        });

Solution 3 - Android

Error is coming in your code from this statement as you said

Intent intent = new Intent(context, SendMessage.class);

This is due to you are providing context of OnItemClickListener anonymous class into the Intent constructor but according to constructor of Intent

android.content.Intent.Intent(Context packageContext, Class<?> cls)

You have to provide context of you activity in which you are using intent that is the MainActivity class context. so your statement which is giving error will be converted to

Intent intent = new Intent(MainActivity.this, SendMessage.class);

Also for sending your message from this MainActivity to SendMessage class please see below code

lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
                Intent intent = new Intent(MainActivity.this, SendMessage.class);
                intent.putExtra(EXTRA_MESSAGE, entry.getMessage());
                startActivity(intent);
            }
        });

Please let me know if this helps you

EDIT:- If you are finding some issue to get the value of list do one thing declear your array list

ArrayList<ListEntry> members = new ArrayList<ListEntry>();

globally i.e. before oncreate and change your listener as below

 lv.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {
                    Intent intent = new Intent(MainActivity.this, SendMessage.class);
                    intent.putExtra(EXTRA_MESSAGE, members.get(position));
                    startActivity(intent);
                }
            });

So your whole code will look as

public class MainActivity extends Activity {
    public final static String EXTRA_MESSAGE = "com.example.ListViewTest.MESSAGE";
ArrayList<ListEntry> members = new ArrayList<ListEntry>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        members.add(new ListEntry("BBB","AAA",R.drawable.tab1_hdpi));
        members.add(new ListEntry("ccc","ddd",R.drawable.tab2_hdpi));
        members.add(new ListEntry("assa","cxv",R.drawable.tab3_hdpi));
        members.add(new ListEntry("BcxsadvBB","AcxdxvAA"));
        members.add(new ListEntry("BcxvadsBB","AcxzvAA"));
        members.add(new ListEntry("BcxvBB","AcxvAA"));
        members.add(new ListEntry("BvBB","AcxsvAA"));
        members.add(new ListEntry("BcxvBB","AcxsvzAA"));
        members.add(new ListEntry("Bcxadv","AcsxvAA"));
        members.add(new ListEntry("BcxcxB","AcxsvAA"));
        ListView lv = (ListView)findViewById(R.id.listView1);
        Log.i("testTag","before start adapter");
        StringArrayAdapter ad = new StringArrayAdapter (members,this);
        Log.i("testTag","after start adapter");
        Log.i("testTag","set adapter");
        lv.setAdapter(ad);
        lv.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
                        Intent intent = new Intent(MainActivity.this, SendMessage.class);
                        intent.putExtra(EXTRA_MESSAGE, members.get(position).getMessage());
                        startActivity(intent);
                    }
                });
    }

Where getMessage() will be a getter method specified in your ListEntry class which you are using to get message which was previously set.

Solution 4 - Android

First, the class must implements the click listenener :

implements OnItemClickListener

Then set a listener to the ListView

yourList.setOnItemclickListener(this);

And finally, create the clic method:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this, "You Clicked at ",   
 Toast.LENGTH_SHORT).show();
}

Solution 5 - Android

    //get main activity
    final Activity main_activity=getActivity();

    //list view click listener
    final ListView listView = (ListView) inflatedView.findViewById(R.id.listView_id);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String stringText;

            //in normal case
            stringText= ((TextView)view).getText().toString();                

            //in case if listview has separate item layout
            TextView textview=(TextView)view.findViewById(R.id.textview_id_of_listview_Item);
            stringText=textview.getText().toString();                

            //show selected
            Toast.makeText(main_activity, stringText, Toast.LENGTH_LONG).show();
        }
    });

    //populate listview

Solution 6 - Android

According to my test,

  1. implements OnItemClickListener -> works.

  2. setOnItemClickListener -> works.

  3. ListView is clickable by default (API 19)

The important thing is, "click" only works to TextView (if you choose simple_list_item_1.xml as item). That means if you provide text data for the ListView, "click" works when you click on text area. Click on empty area does not trigger "click event".

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser782104View Question on Stackoverflow
Solution 1 - AndroidBlackbeltView Answer on Stackoverflow
Solution 2 - AndroidKapil VatsView Answer on Stackoverflow
Solution 3 - AndroidAbhinav Singh MauryaView Answer on Stackoverflow
Solution 4 - AndroidAvinash GargView Answer on Stackoverflow
Solution 5 - AndroidRijul SudhirView Answer on Stackoverflow
Solution 6 - AndroidChaohsiung HuangView Answer on Stackoverflow