gpt4 book ai didi

java - 找到空游标时如何返回

转载 作者:行者123 更新时间:2023-12-01 11:41:17 25 4
gpt4 key购买 nike

我有以下代码从 SQLite 数据库读取数据。我可以检测到空光标,但我不知道如何摆脱它。我无法将 return 语句移至 if( result != null && result.moveToFirst() 语句内。我得到最后两行日志然后程序崩溃

/CSV Import﹕ cursor index is NOT greater than 0
/CSV Import﹕ Null Cursor Found

代码:

public Equipment getEquipmentByID(int id){
SQLiteDatabase db = this.getReadableDatabase();

String SQL = "SELECT "+EQUIPMENT_TABLE+".*, "+LOCATION_TABLE+"."+LOCATION_NAME+" as locationName FROM "+ EQUIPMENT_TABLE + " " +
"JOIN "+LOCATION_TABLE + " ON "+LOCATION_TABLE+"."+LOCATION_ID+"="+EQUIPMENT_TABLE+"."+EQUIPMENT_LOCATION+" " +
"WHERE "+EQUIPMENT_TABLE+"."+EQUIPMENT_ID +"="+id;

Cursor result = db.rawQuery(SQL, null);
result.moveToFirst();

if(result != null && result.moveToFirst()) {
Log.v("CSV Import", "Null Cursor not Found");
} else {
if (result.getCount()>0) {
Log.v("CSV Import", "cursor index is grater than 0");
} else {
Log.v("CSV Import", "cursor index is NOT greater than 0");
}
Log.v("CSV Import", "Null Cursor Found");
}

Equipment equipment = new Equipment(result.getInt(result.getColumnIndex(EQUIPMENT_ID)), result.getString(result.getColumnIndex(EQUIPMENT_NAME)),
result.getString(result.getColumnIndex(EQUIPMENT_MODEL)), result.getString(result.getColumnIndex(EQUIPMENT_SERIAL)),
result.getString(result.getColumnIndex(EQUIPMENT_NOTES)), new Location(result.getInt(result.getColumnIndex(EQUIPMENT_LOCATION)),
result.getString(result.getColumnIndex("locationName"))), new EquipmentType(1, "Undefined"));
return equipment;
}

最佳答案

From the docs , 如果光标为空,moveToFirst() 将返回 false,否则返回 true。因此,从以下行开始: result.moveToFirst(); 全部替换为:

if(result == null) return null;

if(!result.moveToFirst()) {
result.close();
db.close();
return null;
}

Equipment equipment = new Equipment(result.get //.... and so on ....//);
result.close();
db.close();
return equipment;

关于java - 找到空游标时如何返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29501243/

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