gpt4 book ai didi

android - 更新数据库时出现 CursorIndexOutOfBoundsException

转载 作者:搜寻专家 更新时间:2023-10-30 22:13:59 26 4
gpt4 key购买 nike

这是我遇到的错误:

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

现在,它告诉我在我在别处制作的 toast 中更新了详细信息,但是当我尝试显示更新的详细信息时,我得到了 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);

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

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

最佳答案

查询返回的游标可能为空但绝不会为空。如果它为空,则 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;

关于android - 更新数据库时出现 CursorIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17759089/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com