Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround for needing an _id row for CursorAdapter

Tags:

android

I found out in order for the Android CursorAdapter class to work I need a row _id. Now, I have a specific naming scheme and do not want to change my id column (called ID) to _id for all the tables I need CursorAdapters for. I think this will affect readability of some of my complex queries- plus "_id" is ugly :P.

I'm debating using custom "TableID as _id" select queries, but I like SQLiteDatabase's nice query methods and it doesn't look like they support renaming columns in the query.

It seems rather inflexible (and odd) to always require a specific table column name. Is there a way to specify what column to use as the id column to the CursorAdapter? Or maybe another workaround I haven't thought of?

like image 872
Emily Avatar asked Apr 29 '11 00:04

Emily


2 Answers

There's no need to use a raw query, CursorWrapper, etc. You can do exactly what you mentioned: when you specify the columns for your query, just specify "TableID as _id" as one of them. Actually, instead of _id I would use BaseColumns._ID. Something like this ought to work just fine:

static final String[] columns = new String[] {
    "TableID AS " + BaseColumns._ID,
    ...
};

And then pass that to whatever you're using to create your cursor (SQLiteDatabase, CursorLoader, etc.)

I would also recommend putting your column names into String constants that you can reference throughout your app, e.g. MyDatabase.TABLE_ID, so the above would be MyDatabase.TABLE_ID + " AS " + BaseColumns._ID

like image 188
bmaupin Avatar answered Sep 21 '22 09:09

bmaupin


Your database doesn't need to have a column called '_id' but the CursorAdaptor does need to have one returned. You can do this with an alias (such as your "TableID as _id" idea) in a rawQuery.

An example is that I have a table with columns...

uid,name,number

To query this for a SimpleCursorAdapter (for example), I do this with a database rawQuery...

db.rawQuery("SELECT uid as _id,name,number FROM MY_TABLE");

This works fine and supplies the necessary '_id' column to SimpleCursorAdapter.

like image 36
Squonk Avatar answered Sep 23 '22 09:09

Squonk