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



Solution 1:[1]

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.

Solution 2:[2]

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 :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Baris Demiray
Solution 2