Search code examples
androiddatabaselistviewandroid-listviewidentifier

How to pass along an identifier with an item in ListView?


I have a ListView which contains EMPLOYEE_NAME from a DB table EMPLOYEE. Some employees may have the same name, which means I could have duplicated items in the ListView.

What would be the best solution for identifying which item (employee) the user selected? I know that the event onItemClick returns the View associated with the selected item and doing a ((TextView) view).getText() gets me the employee name.

But what would be the solution for passing the row id along with the employee name? Should I extend TextView to include the row id?


Solution

  • The onItemClick contains a long parameter called id, which is what you would want to use:

    onItemClick(AdapterView<?> parent, View view, int position, long id)
    

    So, if you are using a CursorAdapter the only thing you have to do is making sure that the ID row in the database is called _id.

    If you are using other kind of adapters, say BaseAdapter, you have to override the getItemId method, where you will return the ID of the employee.