IllegalStateException on Cursor

JeffinJ :

I am getting this error when trying to read from the SQLite DB

IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

DbHelper dbHelper = new DbHelper(this);
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = dbHelper.readNumber(database);

String ItemId;

if (cursor.getCount() > 0) {
    while (cursor.moveToNext()) {
        //getting the ERROR here
        ItemId = cursor.getString(cursor.getColumnIndex(DbContract.ITEMID));
        number = cursor.getString(cursor.getColumnIndex(DbContract.PHONE_NUMBER));
        callType = cursor.getString(cursor.getColumnIndex(DbContract.CALL_TYPE));
        callDate = cursor.getString(cursor.getColumnIndex(DbContract.CALL_DATE));
        callDuration = cursor.getString(cursor.getColumnIndex(DbContract.CALL_DURATION));

        arrayList.add(new PhNumber(ItemId, number, callType, callDate, callDuration));
        if (debug) {
            Log.i(TAG, "DATA FOUND IN DB:\n" + "\t ID: " + ItemId + ", Number: " + number + "\n");
        }
    }
    cursor.close();
    dbHelper.close();
    result = true;
    if (debug) {
        Log.d(TAG, " Number of items in DB: " + arrayList.size());
    }
} 

readNumber

public Cursor readNumber(SQLiteDatabase database) {
    String[] projections = {"id", DbContract.PHONE_NUMBER};
    return (database.query(DbContract.TABLE_NAME, projections, null, null, null, null, null));
}

This is my DB

private static final String CREATE = "create table " + DbContract.TABLE_NAME +
        "(id integer primary key autoincrement,"
        + DbContract.ITEMID + " text, "
        + DbContract.PHONE_NUMBER + " text, "
        + DbContract.CALL_TYPE + " text, "
        + DbContract.CALL_DATE + " text, "
        + DbContract.CALL_DURATION + " text, "
        + DbContract.SYNC_STATUS + " text)";
dan :

In your projection, created by readNumber call, you have only the id and PHONE_NUMBER columns returned. Probably DbContract.ITEMID is not equal to id and when trying to lookup the DbContract.ITEMID in the cursor it is not found. To fix this you need to use ITEMID in readNumber method, something like:

public Cursor readNumber(SQLiteDatabase database) {
    String[] projections = {DbContract.ITEMID, DbContract.PHONE_NUMBER};
    return (database.query(DbContract.TABLE_NAME, projections, null, null, null, null, null));
}

Another issue is that you are trying to access other fields too, like: CALL_TYPE, CALL_DATE, etc.

So, in order to fix the issue you either:

  • Do not try to retrieve the fields that are not part of the result.
  • Add the needed fields in the projection too.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159471&siteId=1