Alex Mensak
Alex Mensak

Reputation: 168

android sql cursor error

Im playing with sql in android and found this issue:

Im reading data from my database:

    SQLiteDatabase db = this.getReadableDatabase();
    cursor = db.rawQuery("SELECT * FROM " + TABLE_SINGLE_APPS + " WHERE " + COLUMN_SINGLE_PACKAGE + "=?"
            , new String[]{packageName});

    SingleAppModel singleAppModel = new SingleAppModel();

and when I try to get cursor.getInt(3) over here:

    try {
        if (cursor.getCount() != 0) {
            if (cursor.moveToFirst()) {
                singleAppModel.setId(cursor.getInt(0));
                singleAppModel.setAppName(cursor.getString(1));
                singleAppModel.setPackageName(cursor.getString(2));
                singleAppModel.setState(cursor.getInt(3) == 1);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    cursor.close();
    db.close();

It returns error:

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0`

Weird is that if I delete line where Im calling cursor.getInt(3), it works. Colum with that value exists and Im sure its of type INTEGER.

Also the value of cursor.getColumnCount() is 4 and value of cursor.getCount() is 1 ... so there are definetly some data...

Any advice?

Thankyou.

Upvotes: 0

Views: 52

Answers (1)

diyoda_
diyoda_

Reputation: 5420

Rather than using * I suggest you to use,

 cursor = db.rawQuery("SELECT COL0, COL1, COL2, COL3 FROM " + TABLE_SINGLE_APPS + " WHERE " + COLUMN_SINGLE_PACKAGE + "=?"
            , new String[]{packageName});

Use the appropriate values for COL0, COL1, COL2, COL3 according to your table. That way you make sure that the order of the columns fetched in the query.

But according to this,

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0`

I need more information to confirm, can you add your table schema, according to the issue there is no 3rd column in the database raw.

Edit:

This can be a small programmer mistake,

Look out for the onCreate and onUpgrade methods in SQLiteOpenHelper implementation

Upvotes: 1

Related Questions