亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

讓 Bowler Count 顯示在 League RecyclerView 中

讓 Bowler Count 顯示在 League RecyclerView 中

FFIVE 2023-04-26 17:14:02
我有一個聯賽列表,我想在每個條目中顯示投球手的數量。例如:我想在列表中每個聯賽名稱下顯示每個列表中投球手的數量。例如:這是為了快速了解每個聯賽。我試圖用下面的代碼來完成這個:數據庫助手//Getting Number of Bowlers in League    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 = 0;    if(null != cursor)        if(cursor.getCount() > 0){            cursor.moveToFirst();            count = cursor.getInt(0);        }    cursor.close();db.close();return String.valueOf(count);}幾天來我一直在搞這個,我不明白為什么這行不通。任何幫助將不勝感激。我在想,可能有一種我不知道的更簡單的方法來完成這個。在 logcat 中,我看到以下消息:java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String ca.vogl.r.tenpinbowlingcompanion.database.DatabaseHelper.leagueBowlerCount(java.lang.String)' on a null object reference.正如下面所指出的,錯誤似乎發生在上面列出的 leagueBowlerCount() 中。在對 onBindViewHolder 添加以下內容之后:db = new DatabaseHelper (mainActivity)。我看到了我應該看到的值,但它們不正確。見下圖。
查看完整描述

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,因為無法執行移動。


查看完整回答
反對 回復 2023-04-26
  • 1 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號