Parama Sudha Parama Sudha - 5 months ago 107
Android Question

Calculate Sum of Column in SQLite Android

I need to calculate Sum value of a Column.For that I am using the following query.But the app is crashed when I click a button to calculate.

Cursor cur = db.rawQuery("SELECT SUM " + (DbHelper.CART_TOTAL) + " FROM " + DbHelper.CART_TABLE, null);
if (cur.moveToFirst()) {
Log.e("Net Total", cur.getInt(0) + "");
return cur.getInt(0);
}
return 0;


Logcat error:

android.database.sqlite.SQLiteException:
no such column: SUM (code 1): ,
while compiling: SELECT SUM cart_total FROM cart_table
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253)
at com.insideglobe.restaurant.Db.DbUtil.calculateNetTotal(DbUtil.java:276)
at com.insideglobe.restaurant.Adapter.MyCartAdapter$1.UpdateCart(MyCartAdapter.java:104)
at com.insideglobe.restaurant.Adapter.MyCartAdapter$1.onClick(MyCartAdapter.java:91)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16987)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4794)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)

M D M D
Answer

Correct way

 Cursor cursor = db.rawQuery("SELECT SUM(" + DbHelper.CART_TOTAL + ") as Total FROM " + DbHelper.CART_TABLE, null);

 if (cur.moveToFirst()) {

 int total = cursor.getInt(cursor.getColumnIndex("Total"));// get final total
Comments