1 回答

TA貢獻1824條經驗 獲得超5個贊
我相信您的問題是您返回的是第一個選定的投球手的 ID 而不是行數。
也就是你,檢查行數大于0后,移動到第一行,然后使用count = cursor.getInt(0);這將是已提取的第一行的第一列中存儲的值。
嘗試使用:-
public String leagueBowlerCount(String leagueId)
{
String rv = "0";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Bowler.TABLE_NAME,new String[]{"count(*)"},Bowler.COLUMN_LEAGUE_ID + "=?",new String[]{leagueId},null,null,null);
if (cursor.moveToFirst()) {
rv = String.valueOf(cursor.getLong(0));
}
cursor.close();
db.close();
return rv;
}
這使用聚合函數計數來提取相應聯賽的行數。
請注意,以上代碼是原理代碼,尚未經過測試或運行,因此可能存在一些錯誤。
或者你可以使用: -
public String leagueBowlerCount(String leagueId)
{
SQLiteDatabase db = this.getReadableDatabase();
String countQuery = "SELECT * FROM " + Bowler.TABLE_NAME + " WHERE " + Bowler.COLUMN_LEAGUE_ID + " = '" + leagueId + "'";
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
db.close();
return String.valueOf(count);
}
關于您的代碼:-
int count = 0;
if(null != cursor)
if(cursor.getCount() > 0){
cursor.moveToFirst();
count = cursor.getInt(0);
}
cursor.close();
檢查 null Cursor 是沒有用的,因為從 SQLiteDatabase 方法(例如 rawQuery)返回的 Cursor 永遠不會為 null。相反,將返回一個有效的、可能為空的 Cursor。
此外,使用該方法檢查 Cursor 是否有行getCount,然后moveToFirst不需要使用,因為僅使用if (cursor.moveToFirst) {.....}就足夠了,因為如果沒有行,該moveToFirst方法將返回 false,因為無法執行移動。
添加回答
舉報