onItemClickListener(), how to pass clicked item's data?

ankit rawat picture ankit rawat · Mar 16, 2013 · Viewed 13.3k times · Source

I am using onItemClickListener() with a List. I want to pass name of the item clicked on, and an arbitrary number to next instance of the list. How can this be done? Edit: here is the class:

    public class ListViewA extends Activity{

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ListView lv= (ListView)findViewById(R.id.listview);

        // create the grid item mapping
        String[] from = new String[] {"col_1"};
        int[] to = new int[] {R.id.item2};

        // prepare the list of all records
        List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
        for(int i = 0; i < 10; i++){
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("col_1", "col_1_item_" + i);
            fillMaps.add(map);
            lv.setOnItemClickListener(onListClick);
        }

        // fill in the grid_item layout
        SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.grid_item, from, to);
        lv.setAdapter(adapter);
    }
    private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener(){
    public void onItemClick(AdapterView<?> parent,View view, int position, long id)
    {
        Intent i=new Intent(ListViewA.this,ListViewA.class);
        startActivity(i);
    }

};
}

Answer

Hardik Joshi picture Hardik Joshi · Mar 16, 2013

Following example shows you how to pass data onItemClick for particular position.

ListView lv = getListView();

            // listening to single list item on click
            lv.setOnItemClickListener(new OnItemClickListener() {
              public void onItemClick(AdapterView<?> parent, View view,
                  int position, long id) {

                  // selected item
                HERE YOU GOT POSITION FOR PERTICULAR ITEM

                  // Launching new Activity on selecting single List Item
                  Intent i = new Intent(getApplicationContext(), SingleListItem.class);
                  // sending data to new activity
                  i.putExtra("position", fillMaps.get(position));
                  startActivity(i);

              }
            });

And yes you need to declare fillMaps as globally.

public class ListViewA extends Activity{

    List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);......