OnItemClickListener using ArrayAdapter for ListView

143,038

Solution 1

Use OnItemClickListener

   ListView lv = getListView();
   lv.setOnItemClickListener(new OnItemClickListener()
   {
      @Override
      public void onItemClick(AdapterView<?> adapter, View v, int position,
            long arg3) 
      {
            String value = (String)adapter.getItemAtPosition(position); 
            // assuming string and if you want to get the value on click of list item
            // do what you intend to do on click of listview row
      }
   });

When you click on a row a listener is fired. So you setOnClickListener on the listview and use the annonymous inner class OnItemClickListener.

You also override onItemClick. The first param is a adapter. Second param is the view. third param is the position ( index of listview items).

Using the position you get the item .

Edit : From your comments i assume you need to set the adapter o listview

So assuming your activity extends ListActivtiy

     setListAdapter(adapter); 

Or if your activity class extends Activity

     ListView lv = (ListView) findViewById(R.id.listview1);
     //initialize adapter 
     lv.setAdapter(adapter); 

Solution 2

you can use this way...

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                final int position, long id) {

          String main = listView.getSelectedItem().toString();
        }
    });

Solution 3

Ok, after the information that your Activity extends ListActivity here's a way to implement OnItemClickListener:

public class newListView extends ListView {

    public newListView(Context context) {
        super(context);
    }

    @Override
    public void setOnItemClickListener(
            android.widget.AdapterView.OnItemClickListener listener) {
        super.setOnItemClickListener(listener);
        //do something when item is clicked

    }

}

Solution 4

i'm using arrayadpter ,using this follwed code i'm able to get items

String value = (String)adapter.getItemAtPosition(position);

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
             String string=adapter.getItem(position);
             Log.d("**********", string);

        }
    });
Share:
143,038

Related videos on Youtube

Ahmed Zafar
Author by

Ahmed Zafar

Updated on July 09, 2022

Comments

  • Ahmed Zafar
    Ahmed Zafar almost 2 years

    I want to have an OnItemClickListener for a ListView I create using an ArrayAdapter

    This is the code I use to create it:

    List<Comment> values = datasource.some_search("Wednesday","11");
            ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
                    android.R.layout.simple_list_item_1, values);
            setListAdapter(adapter);
    

    How do I implement onItemClickListener?

    Thanks!

    EDIT: I am using in my ArrayAdapter and ListView a string of objects.

    EDIT 2: More code:

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    
    
            datasource = new CommentsDataSource(this);
            datasource.open();
            //check if database is populated if NOT, populate with txtToDb();
    
            if (!datasource.isPopulated()) {
                // Database is not populated so copy it from assets here
                try {
                    txtToDb();
                    Log.i("Database", "Was not Populated");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.i("Database", "Was not populated: txtToDb(); failed");
    
                }
    
            } else {
                Log.i("Database", "Populated");
            }
    
            //wat to show on screen:
            List<Comment> values = datasource.search("Wednesday","11");
    
    
            // Use the SimpleCursorAdapter to show the
            // elements in a ListView
            ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
                    android.R.layout.simple_list_item_1, values);
            setListAdapter(adapter);
    
        }
    

    EDIT 3: XML:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <LinearLayout
            android:id="@+id/group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
    
            <Button
                android:id="@+id/add"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Add New" 
                android:onClick="onClick"/>
    
            <Button
                android:id="@+id/delete"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Delete First" 
                android:onClick="onClick"/>
    
        </LinearLayout>
    
        <ListView
            android:id="@android:id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/hello" />
    
    </LinearLayout> 
    
    • Piyush
      Piyush almost 11 years
      you can call setonItemClickListner method for that..
    • Ahmed Zafar
      Ahmed Zafar almost 11 years
      @piyush- Can you tell me how? How do I create the method that links it with the ArrayAdapter given above?
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    I don't understand how this method knows that it's linked to the ArrayAdapter above?
  • Piyush
    Piyush almost 11 years
    means you want to get value from adapter??
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    I have the list which is displayed, store in the ArrayAdapter. When I click an item on the list, I want it to do something. Call a number, to be specific. How can I use this method so that it does that? listView is not something that I have specified in my code, can you please tell me more about how this function works and how I will use it. I am confused.
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    I'm confused as to how this method is linked to the array adapter above? Surely I can't just copy paste this and expect it to work. I'm a relative newbie so please explain a little bit more. Thanks.
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    "// assuming string and if you want to get the value on click of list item" I am assuming here is where I type the code that does something if an item is clicked?
  • Piyush
    Piyush almost 11 years
    And if you are call different thing for different item then use switch case also..
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    thanks so much for the reply but I am still confused. Sorry. I have an array adapter declared, and not a listView. Do I need to do something before this method to link the array adapter to the 'listView' that you have show in your method?
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
  • Piyush
    Piyush almost 11 years
    If you have already taken in xml file then find the id of ListView onCreate() method else accroding to Raghunandan you can use that.
  • Raghunandan
    Raghunandan almost 11 years
    @AhmedZafar you can do what you intend to do instead of getting the item when you click the row. exactly
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    Okay. And how do I link ListView lv with my array adapter? That's what's confusing me. Also will I give the function an input or will it automatically know what I am clicking
  • Raghunandan
    Raghunandan almost 11 years
    @AhmedZafar there is no need to link anything. shows us more code your activity code
  • Raghunandan
    Raghunandan almost 11 years
    @AhmedZafar what does your activity class extend ListActivity or Activity and shows us your xml
  • Heisnberg
    Heisnberg almost 11 years
    Does your Activity extends ListActivity?
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    Yes it does! Where do I go from there?
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    I use setListAdapter instead of list.setAdapter(--). Should I be using both?
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    Does "ListView lv = getListView();" automatically link to the listview in that activity?
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    @toddx- Thanks so much. I need to create a new class for this? And if I do I still do not get how does this class link with my original listview? Please clarify this. And thanks for all the help.
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    Wow okay this works but it crashes on String value = (String)adapter.getItemAtPosition(position); so I commented that out and put Log.i("Database", "ITEM CLICKED"); and it does seem to work but the thing is, how do I retrieve data from that click. It has a number stored in it which I want it to call. So the question is that I want to customize this rather than have just one thing happen for every item clicked. Thanks.
  • Raghunandan
    Raghunandan almost 11 years
    @AhmedZafar show us the number you said string and also post the updated logcat no need for customization or anything.
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    Sorry it's not string. I don't remember saying that. Logcat is perfect and says ITEM CLICKED whenever I click an item. In the Adapter are stored Objects with Strings in them. Things like name, contact, day1, from1, etc etc. I want to retrieve these values.
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    @raghun- HOLY (@#*$U* IT WORKED! THANKS SO MUCH! I used Comment comment = (Comment) adapter.getItemAtPosition(position); Log.i("Database", comment.getName()); To print out names to the logcat. Thanks! :) This is the correct answer.
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    Thank you for your help!
  • Ahmed Zafar
    Ahmed Zafar almost 11 years
    Thanks for your help todd !
  • Heisnberg
    Heisnberg almost 11 years
    No problem @AhmedZafar :-)
  • LUKER
    LUKER about 8 years
    How would you get the string of each textview if there are two textviews in each item. I have a Contacts list that I would like to get the value of the number as well as the name. How would I do this? @PiyushGupta would you be able to help me please?