1 回答

TA貢獻1906條經驗 獲得超3個贊
刪除表名稱周圍的單引號:
Cursor cursor = database.rawQuery("select * from " + PRODUCTS +";", null);
需要單引號來包裹字符串文字。
還要用 while 循環替換 for 循環(上限錯誤):
private void getTotal() {
int m=0;
Cursor cursor = db.gettotal();
if (cursor.getCount() == 0) {
Toast.makeText(getApplicationContext(),"No message is available", Toast.LENGTH_LONG).show();
} else {
while (cursor.moveToNext()) {
m += cursor.getInt(cursor.getColumnIndex("amount"));
}
total_amount.setText("" + m);
}
}
我更換了:
String.valueOf(cursor.getColumnIndex("amount"))
它返回列的索引位置:
cursor.getInt(cursor.getColumnIndex("amount"))
它返回列的值。
我也更換了:
total_amount.setText(m);
這是問題的根源,因為它m是一個整數,被視為資源而不是文本,具有:
total_amount.setText("" + m);
此外,如果您想要的只是列的總和,amount您可以執行此查詢:
Cursor cursor =database.rawQuery("select sum(amount) as total from " + PRODUCTS + ";", null);
所以你只需要得到這個查詢返回的唯一的行和列,你不需要任何循環來計算總數。
添加回答
舉報