Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

sqlite - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...