游标上的IllegalStateException

时间:2019-03-05 10:35:47

标签: java android sqlite

尝试从SQLite数据库读取时出现此错误

  

IllegalStateException:无法从CursorWindow读取行0,col -1。在从游标访问数据之前,请确保游标已正确初始化。

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));
}

这是我的数据库

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)";

2 个答案:

答案 0 :(得分:0)

在通过readNumber调用创建的投影中,仅返回了idPHONE_NUMBER列。可能DbContract.ITEMID不等于id,并且在尝试在光标中查找DbContract.ITEMID时找不到它。要解决此问题,您需要在ITEMID方法中使用readNumber,例如:

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

另一个问题是您也尝试访问其他字段,例如:CALL_TYPECALL_DATE等。

因此,要解决此问题,您可以:

  • 请勿尝试检索不属于结果的字段。
  • 也在投影中添加所需的字段。

答案 1 :(得分:0)

发现了问题: 我试图访问readNumber方法中未添加到项目中的列,添加这些投影解决了该问题。

  

readNumber

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