What's the purpose of item-id's in Android ListView Adapter?

Randy Sugianto 'Yuku' picture Randy Sugianto 'Yuku' · Feb 24, 2011 · Viewed 15.2k times · Source

(Not specific to ListView, but to Adapter).

I keep implementing this when I subclass BaseAdapter:

    @Override
    public long getItemId(int position) {
        return position; 
    }

Because have to implement that. I don't see any use of it, I need getItem(position) only, not getItemId(position).

I wonder if it has any significance (to Android SDK or something else)?

Answer

Gramotei picture Gramotei · Mar 25, 2012

Imagine this structure:

You have db table Notes with such 3 records:

+----+--------------------------+
| ID | Note Text                |
+----+--------------------------+
| 43 | Note text blah blah      |
| 67 | Note text blah blah blah |
| 85 | Last note                |
+----+--------------------------+

and you implement an adapter to serve this data.

Now let's see what position and item id are in such a case

position - is an ordinal number of record position in the loaded dataset. For example if you load that table with ORDER BY ID ASC, then

  • record with ID 43 will have position 0,
  • record with ID 67 will have position 1,
  • record with ID 85 will have position 2

itemId - is a "primary key" of a record, and your implementation can return such values

  • record with ID 43 should have itemId 43,
  • record with ID 67 should have itemId 67,
  • record with ID 85 should have itemId 85

position and itemId in Android standard adapters

ArrayAdapter / SimpleAdapter

In ArrayAdapter and SimpleAdapter position and itemId is the same thing:

public long getItemId(int position) {
    return position; 
}

SimpleCursorAdapter (and all types that inherit from CursorAdapter)

In the SimpleCursorAdapter and all descendants of CursorAdapter itemId is a value from _id column:

public long getItemId(int position) {
    if (mDataValid && mCursor != null) {
        if (mCursor.moveToPosition(position)) {
            return mCursor.getLong(mRowIDColumn);
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}