Return sum(item_price) 来自 Android 中的 sqlite

Return sum(item_price) from sqlite in Android

我正在尝试从数据库中的特定列中获取总和。我认为我的查询没问题,但我认为收到它有问题。请指引我正确的道路。

在此先感谢您。

public static double countPrice (SQLiteDatabase db, int selectedID){
    String[] sumPrice = new String[]{"sum(item_price)"};
    String selection = "list_id =? AND item_flag =?";
    String[] selectionArgs = new String[]{String.valueOf(selectedID), String.valueOf(0)};

    Cursor c = db.query(TABLE_NAME, sumPrice, selection, selectionArgs, null, null, null);

    double result = c.getCount();
    return result;
}

您返回的是 cursor.getCount() returns 行数而不是总和。 Android Cursor

使用以下代码:

Cursor cur = db.rawQuery("SELECT SUM(myColumn) FROM myTable", null);
if(cur.moveToFirst())
{

return cur.getInt(0);
}

您正在使用 Cursor getCount() 方法,该方法将 return 行数,这将是 1,因为查询是 returning 聚合(即总和)。

相反,您需要

  • a) 移动到光标的第一行然后
  • b) read/extract 使用适当的 Cursor get??? 方法来自相应列的数据。

因此您的代码可以是:-

public static double countPrice (SQLiteDatabase db, int selectedID){
    String[] sumPrice = new String[]{"sum(item_price)"};
    String selection = "list_id =? AND item_flag =?";
    String[] selectionArgs = new String[]{String.valueOf(selectedID), String.valueOf(0)};

    Cursor c = db.query(TABLE_NAME, sumPrice, selection, selectionArgs, null, null, null);

    Double result = 0; // default value to signify nothing extracted
    if(c.moveToFirst()) { // move to the first(only) row in the Cursor
        result = c.getDouble(0); // get the value from the first column
    }
    c.close(); // Should always close cursors when done with them
    return result; // Ok to return extracted value (or default for nothing extracted)
}