如何从sqlite数据库中获取总量值

我正在尝试为计费系统创建一个应用程序。这些值被插入到数据库中并成功检索。另外,我需要数据库中的总金额。


数据库辅助类


public Cursor gettotal()

    {

        SQLiteDatabase database = this.getReadableDatabase();

        Cursor cursor =database.rawQuery("select * from '"+PRODUCTS+"' ;", null);

        Log.d(TAG, "gettotal: "+cursor.getCount());

        return cursor;


    }

总计


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

        {

            for(int k = 0; k<=cursor.getCount();k++) {

                m += (int) Integer.parseInt(String.valueOf(cursor.getColumnIndex("amount")));

            }

            i=m;

            total_amount.setText(m);

        }

}

我的日志猫


D/MainActivity: getTotal: -1

E/uetooth_embade: Invalid ID 0x00000008.

D/AndroidRuntime: Shutting down VM

E/AndroidRuntime: FATAL EXCEPTION: main

    Process: com.example.bluetooth_embaded, PID: 14063

    android.content.res.Resources$NotFoundException: String resource ID #0x8

        at android.content.res.Resources.getText(Resources.java:360)

        at android.content.res.MiuiResources.getText(MiuiResources.java:97)

        at android.widget.TextView.setText(TextView.java:5837)

        at com.example.bluetooth_embaded.MainActivity.getTotal(MainActivity.java:100)

        at com.example.bluetooth_embaded.MainActivity.access$200(MainActivity.java:33)

        at com.example.bluetooth_embaded.MainActivity$5.onClick(MainActivity.java:181)

        at android.view.View.performClick(View.java:6616)

        at android.view.View.performClickInternal(View.java:6593)

        at android.view.View.access$3100(View.java:785)

I/Process: Sending signal. PID: 14063 SIG: 9


慕尼黑8549860
浏览 251回答 1
1回答

一只名叫tom的猫

删除表名称周围的单引号:Cursor cursor = database.rawQuery("select * from " + PRODUCTS +";", null);需要单引号来包裹字符串文字。还要用 while 循环替换 for 循环(上限错误):private void getTotal() {&nbsp; &nbsp; int m=0;&nbsp; &nbsp; Cursor cursor = db.gettotal();&nbsp; &nbsp; if (cursor.getCount() == 0) {&nbsp; &nbsp; &nbsp; &nbsp; Toast.makeText(getApplicationContext(),"No message is available", Toast.LENGTH_LONG).show();&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; while (cursor.moveToNext()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m += cursor.getInt(cursor.getColumnIndex("amount"));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; total_amount.setText("" + m);&nbsp; &nbsp; }}我更换了: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);所以你只需要得到这个查询返回的唯一的行和列,你不需要任何循环来计算总数。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java