Search code examples
androidandroid-sqlitesqliteopenhelper

I can't get data from Cursor Object


I've following table structure in my SQLite Database. enter image description here

In my SqliteOpenHelper class, I wrote following method.

public Form getAllForms(){
   SQLiteDatabase db = this.getReadableDatabase();
   Cursor cursor = db.rawQuery("select * from "+FORM_TABLE, null);
   int count = cursor.getCount();
   String formID = cursor.getString(0);
   Form form = new Form();
   form.setId(formID);
   cursor.close();
   db.close();
   return form;
}

I'm sure there's some data in it because I already watched count in debugging mode and I saw the quantity of row that actually existing in database. But CursorIndexOutOfBoundException shows up at cursor.getString(0). plus cursor.getInt(0) and cursor.getString(1) didn't work also. What's the problem might be?


Solution

  • You need to move the cursor to a valid row.

    Valid rows are indexed from 0 to count-1. At first the cursor will point to row index -1 i.e. the one just before the first row.

    The canonical way of looping through all rows is

    if (cursor.moveToFirst()) {
        do {
             // now access cursor columns
        } while (cursor.moveToNext());
    }