I have created an SQLiteOpenHelper subclass to store reminders.
I create a table in this class as follows:
public static final String TABLE = "Reminders";
public static final String ID = "id";
public static final String COMPLETE = "complete";
public static final String PRIORITY = "priority";
public static final String DATE = " alarmdate";
public static final String TITLE = "title";
public static final String NOTES = "notes";
@Override
public void onCreate(SQLiteDatabase db) {
String create = "CREATE TABLE " + TABLE + "(\n"
+ ID + " INTEGER PRIMARY KEY, \n"
+ COMPLETE + " INTEGER DEFAULT 0, \n"
+ PRIORITY + " INTEGER DEFAULT 1, \n"
+ DATE + " CHAR(21) DEFAULT NULL, \n"
+ TITLE + " TEXT NOT NULL, \n"
+ NOTES + " TEXT DEFAULT NULL \n"
+ ");";
db.execSQL(create);
}
The database is created fine and I am able to add entries normally.
The problem is that, when I want to retrieve a row from the database, cursor.getColumnIndex(DATE) returns -1, while it returns the correct indexes for the other fields:
//Method of the helper class
public Reminder getReminder(int _id) {
Reminder r;
SQLiteDatabase db = getReadableDatabase();
String query = String
.format("SELECT * FROM %s WHERE ID=%d", TABLE, _id);
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
if (cursor.isAfterLast())
return null;
boolean complete = (cursor.getInt(cursor.getColumnIndex(COMPLETE)) != 0);
int priority = cursor.getInt(cursor.getColumnIndex(PRIORITY));
String dateS = cursor.getString(cursor.getColumnIndex(DATE)); //cursor.getColumnIndex(DATE) returns -1;
//etc...
cursor.close();
It’s quite annoying, as getColumnIndex() returns a valid index for all the other fields.
Even more, calling cursor.getString(3) instead of cursor.getString(cursor.getColumnIndex(DATE)), I get the date value correctly.
What might be the cause of this and how could I fix it?
Try removing the leading space from
" alarmdate".If that doesn’t do it, try changing
CHAR(21)toTEXT, which means exactly the same as far as SQLite is concerned.