Glave Glave - 22 days ago 5
Android Question

CursorIndexOutOfBoundsException during my query [SQLite]

I want to search my database for a row where

KEY_TOR == place.getTor()


Here I call the method:

DB_Place tor = db_tore.getDBPlace(place.getTor());


This is the method:

public DB_Place getDBPlace(String name) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_DB_TORE_Eintrag, new String[] { KEY_ID,
KEY_PLACE_ID, KEY_NAME, KEY_LONGITUDE, KEY_LATITUDE, KEY_TOR }, KEY_TOR + "=?",
new String[]{name}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

DB_Place place = new DB_Place(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));

return place;
}


Looks good to me, except that I am getting this error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.x.x/com.example.ahok.x.UI_MainActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0


What am I missing here? Is it possible that it has something to do with a few of the columns being
null
?

Answer

Looks like you don't have any data inserted in your database. Moreover, you've some logical error in your code.

I would like to edit your function like this.

public DB_Place getDBPlace(String name) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_DB_TORE_Eintrag, new String[] { KEY_ID,
                    KEY_PLACE_ID, KEY_NAME, KEY_LONGITUDE, KEY_LATITUDE, KEY_TOR }, KEY_TOR + "=?",
                    new String[]{name}, null, null, null, null);

    DB_Place place = null;

    if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {

        place = new DB_Place(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
    }

    return place;
}

Update

So if you think its an error of your query, then run simple query like this.

Cursor cursor = db.rawQuery("Select * from " + TABLE_DB_TORE_Eintrag + " where " + KEY_TOR + " = " + name, null);
Comments