更新数据库时CursorIndexOutOfBoundsException

时间:2013-07-20 05:42:30

标签: android database sqlite android-sqlite

这是我得到的错误:

07-20 11:04:45.564: E/AndroidRuntime(1905): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dosemanager1.ui/com.dosemanager.ui.ActivityDisplayMedicineDetails}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

我想更新特定药物的详细信息。所以,我使用这段代码:

public int updateMedicine(MedicineDetails medicine, String oldTitle){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_DOSE_NAME, medicine.getDoseName());
    values.put(KEY_DOSE_SCHEDULE, medicine.getDoseSchedule().getTimeInMillis());
    values.put(KEY_DOSE_REPEAT, medicine.getDoseRepeat());
    values.put(KEY_DOSE_FREQUENCY, medicine.getDoseFrequency());
    values.put(KEY_DOSE_OTHER_NOTES, medicine.getOtherNotes());

    // updating row
    return db.update(TABLE_MEDICINES, values, KEY_DOSE_NAME + " = ?",
            new String[] { oldTitle });
}

现在,它告诉我细节是在我在其他地方制作的吐司中更新的,但是当我尝试显示更新的细节时,我得到CursorIndexOutOfBounds例外。

这是我返回单个MedicineDetails对象的代码:

public MedicineDetails getSingleMedicine(String title) {
    SQLiteDatabase db = this.getReadableDatabase();
    Calendar cal = Calendar.getInstance();
    Cursor cursor = db.query(TABLE_MEDICINES, new String[] { KEY_ID_DOSE, KEY_DOSE_NAME, KEY_DOSE_SCHEDULE, 
            KEY_DOSE_REPEAT, KEY_DOSE_FREQUENCY, KEY_DOSE_OTHER_NOTES},
            KEY_DOSE_NAME + "=?",
            new String[] { title }, null, null, null);

    if (cursor != null)
        cursor.moveToFirst();

    cal.setTimeInMillis(cursor.getLong(2));
    System.out.println(cal.getTime());

    MedicineDetails singleDetail = new MedicineDetails(cursor.getString(1), cal,
            cursor.getString(3), cursor.getString(4), cursor.getString(5));

    return singleDetail;
}

这是我创建表格的地方:

String CREATE_MEDICINES_TABLE = "CREATE TABLE " + TABLE_MEDICINES + "("
            + KEY_ID_DOSE + " INTEGER PRIMARY KEY," + KEY_DOSE_NAME + " TEXT,"              
            + KEY_DOSE_SCHEDULE + " INTEGER, " + KEY_DOSE_REPEAT + " TEXT," 
            + KEY_DOSE_FREQUENCY + " TEXT," + KEY_DOSE_OTHER_NOTES + " TEXT" + ");";
    db.execSQL(CREATE_MEDICINES_TABLE);     

相同的代码可以完美地显示我未编辑的任何药物的详细信息。所以,我认为更新有问题。

我已经阅读了一些类似的问题,但其他地方的答案都无法解决我的问题。 我犯了什么错误?

1 个答案:

答案 0 :(得分:3)

查询返回的游标可能为空但从不为null。如果它为空,则moveToFirst()将返回false,因此您的代码应为

MedicineDetails singleDetail;
if (cursor.moveToFirst())
{
    cal.setTimeInMillis(cursor.getLong(2));
    System.out.println(cal.getTime());

    MedicineDetails singleDetail = new MedicineDetails(cursor.getString(1), cal,
        cursor.getString(3), cursor.getString(4), cursor.getString(5));
}

return singleDetail;