Android sqlite db.query leads to CursorIndexOutOfBoundsException

a 夏天 提交于 2019-12-11 18:28:17

问题


I am trying to select certain rows from my database, but since I kept getting index out of bound I decided to remove the WHERE part for now and just get all of the data. I have used the android tutorial http://developer.android.com/training/basics/data-storage/databases.html#DbHelper , in order to create this method. But when I am trying to get values from the query I am getting CursorIndexOutOfBoundsException.

My Code:

String getSite() {
    SQLiteDatabase db = this.getReadableDatabase();
            //get all data for now
    Cursor c = db.query(
        TABLE_NAME,  // The table to query
        null,                               // The columns to return
        null,                                // The columns for the WHERE clause
        null,                            // The values for the WHERE clause
        null,                                     // don't group the rows
        null,                                     // don't filter by row groups
        null                                 // don't sort
        );
    c.moveToFirst();
        String test= c.getString(0); 
    c.close();
    return test;}
}

The Error: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 6

when I checked for c.count() I got 6, so I am not sure why I am referring to an index that might out of bound

Thank you


回答1:


Your cursor is empty if it didn't move.

try

if (c.moveToFirst()) {
    String test= c.getString(0);
    // or String test= c.getString(c.getColumnIndex("column_name")); 
}


来源:https://stackoverflow.com/questions/14446494/android-sqlite-db-query-leads-to-cursorindexoutofboundsexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!