CursorIndexOutOfBoundsException:请求索引0,大小为0

时间:2015-09-08 18:46:56

标签: java android sqlite

我已经实现了一个返回布尔值为true的SQL语句,即表中存在的用户名和日期。以下是我的实施。我还包括了Logcat中显示的当前错误

public boolean flagExists(String Username, String Date) {
SQLiteDatabase db = getReadableDatabase();
String selectString = "SELECT * FROM " + TABLE_FLAGS + " WHERE " + COLUMN_FLAGS_USERNAME + " = '" + Username + " ' " + " AND " + COLUMN_FLAGS_DATE + "= '" + Date + "'";

// Add the String you are searching by here.
// Put it in an array to avoid an unrecognized token error
Cursor cursor = db.rawQuery(selectString, new String[]{Username,Date});

boolean hasObject = false;
if (cursor.moveToFirst()) {
    hasObject = true;

    //region if you had multiple records to check for, use this region.
    int count = 0;
    while (cursor.moveToNext()) {
        count++;
    }
    //here, count is records found
    Log.d(TAG, String.format("%d records found", count));

    //endregion

}
cursor.close();          // Dont forget to close your cursor
db.close();              //AND your Database!
return hasObject;

}

rocess: com.example.s210121629.myhealth, PID: 10953
    android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
            at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
            at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
            at android.database.AbstractWindowedCursor.getDouble(AbstractWindowedCursor.java:86)
            at com.example.s210121629.myhealth.Database.DBHelper.getPerson(DBHelper.java:400)
            at com.example.s210121629.myhealth.dashboard.DashboardActivity.decisionAlgorithm(DashboardActivity.java:347)
            at com.example.s210121629.myhealth.dashboard.DashboardActivity.reloadlist(DashboardActivity.java:327)
            at com.example.s210121629.myhealth.dashboard.DashboardActivity$3.onFinish(DashboardActivity.java:252)
            at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:118)
            at android.os.Handler.dispatchMessage(Handler.java:102)

2 个答案:

答案 0 :(得分:0)

更改

Cursor cursor = db.rawQuery(selectString, new String[]{Username,Date});

Cursor cursor = db.rawQuery(selectString, null);

如果您想指定selectionArgs参数,则selectString必须包含一些? s等于selectionArgs String[]的长度

答案 1 :(得分:0)

更改

String selectString = "SELECT * FROM " + TABLE_FLAGS + " WHERE " + COLUMN_FLAGS_USERNAME + " = '" + Username + " ' " + " AND " + COLUMN_FLAGS_DATE + "= '" + Date + "'";

String selectString = "SELECT * FROM " + TABLE_FLAGS + " WHERE " + COLUMN_FLAGS_USERNAME + " = '" + Username + "' " + " AND " + COLUMN_FLAGS_DATE + "= '" + Date + "'";

您正在为Username变量添加额外空格。