Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: column '_id' does not exist

I am getting this error

IllegalArgumentException: column '_id' does not exist

When using a SimpleCursorAdapter to retrieve from my database, and the table does indeed have this _id column. Noticing this a common problem, I have tried to work around it given some of the solutions online but none of them work. This is my cursor query:

SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.quoterow, myCursor, new String[]{"_id", "quote"}, new int[]{R.id.quote});

although I should mention the original did not include the _id column, I added this recently to try and solve the problem. Has anyone got any ideas that might help solve the problem?

like image 815
MindDrip Avatar asked Apr 28 '11 21:04

MindDrip


1 Answers

Your database doesn't have to have a column called '_id' but the SimpleCursorAdaptor does need to have one returned. You can do this with an alias.

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

uid,name,number

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

SELECT uid as _id,name,number FROM MY_TABLE

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

EDIT: As far as I understand it the _id field is used as a unique key to make sure the data the cursor handles can be handled correctly by adapters and adapterviews etc.

Look at the data model in the docs for Content Providers.

Using a unique key in 'databases' of whatever kind is pretty much universal practice, and as far as I can tell, the use of the column name '_id' (or '_ID') is simply a way of standardizing and simplifying things across databases, content providers, cursors, adapters etc etc

In short, in order for these various components to work correctly, they need a data column with unique values but they must also 'know' what the name of that column is. They wouldn't 'know', so to speak, that my column name 'uid' is the one they need as opposed to my 'name' and 'number' columns.

like image 156
Squonk Avatar answered Oct 01 '22 09:10

Squonk