Search code examples
androidsqliteandroid-cursoradapter

Using String as _id in CursorAdapter


It's a requirement of using a CursorAdapter that:

The Cursor must include a column named "_id" or this class will not work.

It's clear from the getItemId() signature, and the CursorAdapter source, that this column is expected to be an integral type:

/**
 * @see android.widget.ListAdapter#getItemId(int)
 */
public long getItemId(int position) {
    if (mDataValid && mCursor != null) {
        if (mCursor.moveToPosition(position)) {
            return mCursor.getLong(mRowIDColumn);
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}

I'd really like to be able to use another column which contains text (UUID strings) as my _id, but it doesn't look like that's directly possible.

If my database schema (which is defined externally) does not include an integer _id column, what options do I have for coercing a non-integer column, or manufacturing an _id column in the query output?


Solution

  • If my database schema (which is defined externally) does not include an integer _id column, what options do I have for coercing a non-integer column, or manufacturing an _id column in the query output?

    Each sqlite row has a unique ROWID that is an integer. You can select it as the ID:

    String[] columns = new String[] { "rowid AS _id", ... };
    

    If your table happens to have an INTEGER PRIMARY KEY column, it will be aliased with the rowid.

    Reference: https://www.sqlite.org/lang_createtable.html#rowid