Home » Android » SQLite cannot find column

SQLite cannot find column

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’m creating my first android app and I’m having difficulties using sqlite. I’m using the following code to create my table. It works fine for the 3 first columns (_ID, COL_TITLE and COL_MAX) but I can’t seem to create the last column.

String createTable = "CREATE TABLE " + TaskContract.Entry.TABLE + " (" +
                TaskContract.Entry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                TaskContract.Entry.COL_TITLE + " TEXT NOT NULL, " +
                TaskContract.Entry.COL_MAX + " REAL, " +
                TaskContract.Entry.COL_INCREMENT + " REAL " +
                ");";

I tried getting the column index like this:

        Cursor cursor = db.query(TaskContract.Entry.TABLE,
                new String[]{TaskContract.Entry._ID,
                        TaskContract.Entry.COL_TITLE,
                        TaskContract.Entry.COL_MAX},
                TaskContract.Entry._ID + " = ?",
                new String[]{String.valueOf(id)},
                null, null, null);

        int idx_id = cursor.getColumnIndex(TaskContract.Entry._ID); //returns 0
        int idx_title = cursor.getColumnIndex(TaskContract.Entry.COL_TITLE); //returns 1
        int idx_max = cursor.getColumnIndex(TaskContract.Entry.COL_MAX); //returns 2
        int idx_inc = cursor.getColumnIndex(TaskContract.Entry.COL_INCREMENT); //returns -1

As you can see getColumnIndex returns -1 for COL_INCREMENT

I also tried reading the data like this:

cursor.getString(3)

Looks as if the table only contains 3 column and I don’t know where I went wrong. I’ve tried updating database version and uninstalling the app.

Answers:

You need to pass TaskContract.Entry.COL_INCREMENT in your query too. Its missing out currently in your query.

Cursor cursor = db.query(TaskContract.Entry.TABLE,
            new String[]{TaskContract.Entry._ID,
                    TaskContract.Entry.COL_TITLE,
                    TaskContract.Entry.COL_MAX,
                    TaskContract.Entry.COL_INCREMENT},
            TaskContract.Entry._ID + " = ?",
            new String[]{String.valueOf(id)},
            null, null, null);