android - 从 Android 中的 sqlite 返回 sum(item_price)
问题描述
我正在尝试从数据库中的特定列中获取总和。我认为我的查询没问题,但我认为收到它有问题。请指导我正确的方式。
非常感谢你。
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;
}
解决方案
您正在使用 CursorgetCount()
方法,该方法将返回行数,当查询返回聚合(即总和)时,行数将为 1。
相反,您需要
- a) 移动到光标的第一行,然后
- b) 使用适当的 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)
}
推荐阅读
- android - 从 mongodb 检索数据并从 html 插入到脚本中
- php - 在没有作曲家的情况下包含外部库的问题
- c - ZeroMQ - 为一台服务器模拟多个客户端的标准套接字
- python - 如何根据月份替换熊猫数据框行值
- cookies - 自定义 Google Analytics 的 cookie 过期时间......但有 2 个跟踪器
- python - plotly 箱线图中栅栏的定义
- android - 日历日期验证未返回正确的布尔值
- django - Django中的ModelForm验证
- json - 如何进行 API 查询并显示 Json 结果?
- c# - 在 WPF 中查看有错误的应用程序