Search code examples
androidandroid-arrayadapteronitemclicklistener

How to set the correct row id to use in onItemClick?


I have onItemClick listener, and I'd like to use the id value. But it has the same value as position.

public void onItemClick(AdapterView<?> a, View view, int position, long id) {
    DBh.something(id);
}

I'm using a custom ArrayAdapter similar to the one described here: onItemClickListener with custom adapter and listview

I also tried to use row.setId(), but its int not long.


Solution

  • I am not asking why you're trying to do this (you probably have your reasons), so will just explain how to do it. As you are already implementing a custom adapter, all you need to do is override the getItemId method:

    @Override
    public long getItemId(int position) {
        //return ID based on the position
        return ...;
    }
    

    Then this value will be passed into other methods that receive item IDs. Note that if you know how to get the ID from the position, then you can just do it straight in the onItemClickListener, as the position is passed into it.