如何在Android中获取游标检索值的值的总和

时间:2014-08-21 07:31:27

标签: android

我使用下面给出的查询从DB中检索了一些值。

public Cursor getcredittranscation(String date)

{

String sql="SELECT A.Acc_No,A.Cust_Name, T.Trans_Amnt FROM TransactionTable "
            + "T LEFT JOIN AccMaster A on A.Acc_ID = T.Acc_ID "
            + "WHERE T.Trans_Date =? AND T.Trans_Type=? ORDER BY  T.Entry_Time asc";
Cursor cursor = db.rawQuery(sql, new String[]{date, "credit"});

return cursor;
}

在主要活动中,我想将这些结果显示为报告。活动代码如下所示。

try{

            db.open();
            Cursor c = db.getdebittranscation(temp);

            if (c.moveToFirst()) {
                do {
                    DisplayDebitDetails(c);
                    debittotal(c);
                } while (c.moveToNext());
            }
            db.close();
            }catch (Exception e) {
                // TODO: handle exception
                Log.e("Retrive Debit Error ", " "+e.getMessage());
            }
private void DisplayDebitDetails(Cursor c) {

            String tempdebit = debitView.getText().toString() + "  ";
            tempdebit= " \t"+tempdebit+ "\n\t" +c.getString(0) + "\t\t\t" 
                            + c.getString(1) + "\t\t\t" + c.getString(2);
                debitView.setText(tempdebit);

                Log.e("debit", "Acc No :"+c.getString(0) +"Name :"+c.getString(1)+ "Trans Amnt :"+c.getString(2));
            }
        }
        private void debittotal(Cursor c){

   int tmp = Integer.parseInt(debiTotalView.getText().toString()+" ");
            tmp = +tmp+Integer.parseInt(c.getString(2));
            debiTotalView.setText(tmp);

检索和查看所有值都可以......但我需要String(2)中所有值的总和。它以方法debittotal(光标c)给出。那部分的错误是什么?我没有得到总数

2 个答案:

答案 0 :(得分:2)

你可以使用getCount()方法

int number_of_records = cursor.getCount();

答案 1 :(得分:0)

尝试此操作并确保debitTotalView.getText().toString()不是空白或空

最初该字段值必须为0 否则会为NumberFormatException提供invalid int

替换

int tmp = Integer.parseInt(debiTotalView.getText().toString()+" ");
            tmp = +tmp+Integer.parseInt(c.getString(2));
            debiTotalView.setText(tmp);

   int tmp = Integer.parseInt(debiTotalView.getText().toString().trim());
        tmp = +tmp+Integer.parseInt(c.getString(2));
        debiTotalView.setText(tmp+"");