1

这是我得到的错误:

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

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

我读过一些类似的问题,但其他地方的答案都不能解决我的问题。我犯了什么错误?

4

1 回答 1

3

查询返回的游标可能为空,但绝不为空。如果它是空的,那么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;
于 2013-07-20T06:05:04.550 回答