Jake Moritz
Jake Moritz

Reputation: 873

Cursor.getColumnIndex() returns -1 for a column that exists

I'm writing code that will upgrade my app's database to a new version. While upgrading, I drop a table and re-create it with a different schema (including a new column). When I attempt to read data from this new table, I create a cursor like so:

Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_ALARMS, null);

And when I try to read data from the new column, cursor.getColumnIndex(NEW_COLUMN) returns -1, meaning it doesn't exist. This isn't correct as the new column is included in the new schema. Does anyone know why this would happen?

Upvotes: 2

Views: 742

Answers (2)

Baris Demiray
Baris Demiray

Reputation: 1607

There is no problem with the column, you can verify that by getColumnNames() or getColumnCount() on your Cursor.

What's missing is the index of your Cursor, as stated in rawQuery documentation the return value is,

A Cursor object, which is positioned before the first entry.

So initially it is not valid and you need to do a moveFirst() or a moveNext() before accessing data.

Upvotes: 2

seven_seas
seven_seas

Reputation: 723

I'm not sure but I had a problem where my cursor wouldnt read all entrys of a table ( the ones i just create didnt work ) i solved it by closing the cursor and reopening it try that :)

Upvotes: 0

Related Questions