I am having a problem using SQL query with SUM. Im showing the date and number of grams in the list. Without SUM, it displays the date and the penalty gram, but it does not sum the number of grams if there are several records for the same date. SQL query works when I test it in sqlite database browser. The following is part of my code for this:
//attempt 1: public Cursor getOverviewDate(){ String[] columns = new String[]{ C_ID, C_DATE, "sum(" + C_GRAM + ")" }; Cursor cursor = db.query(TABLE, columns, null, null, C_DATE, null, null); return cursor; }
Ive also tried with rawquery:
//attempt 2: public Cursor getOverviewDate(){ String test = "SELECT _id, date, SUM(gram) FROM nutvalues GROUP BY date;"; Cursor cursor = db.rawQuery(test, null); return cursor; }
How the query results are displayed:
mySQLiteAdapter = new CalorieCounterDbAdapter(this); mySQLiteAdapter.open(); Cursor cursor = mySQLiteAdapter.getOverviewDate(); startManagingCursor(cursor); final String[] columns = { CalorieCounterDbAdapter.C_DATE, CalorieCounterDbAdapter.C_GRAM}; int[] to = new int[]{R.id.date, R.id.gram}; SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, columns, to); listContent.setAdapter(cursorAdapter); mySQLiteAdapter.close();
I think one of the errors displayed in logcat is the key to the solution:
01-07 14:31:27.686: E/AndroidRuntime(10497): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 01-07 14:31:27.686: E/AndroidRuntime(10497): at dalvik.system.NativeStart.main(Native Method) 01-07 14:31:27.686: E/AndroidRuntime(10497): Caused by: java.lang.IllegalArgumentException: column 'gram' does not exist 01-07 14:31:27.686: E/AndroidRuntime(10497): at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:314) 01-07 14:31:27.686: E/AndroidRuntime(10497): at android.widget.SimpleCursorAdapter.findColumns(SimpleCursorAdapter.java:312) 01-07 14:31:27.686: E/AndroidRuntime(10497): at android.widget.SimpleCursorAdapter.<init>(SimpleCursorAdapter.java:87) 01-07 14:31:27.686: E/AndroidRuntime(10497): at com.korsakopf.caloriecounter.CalorieCounterOverviewActivity.onCreate(CalorieCounterOverviewActivity.java:39) 01-07 14:31:27.686: E/AndroidRuntime(10497): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 01-07 14:31:27.686: E/AndroidRuntime(10497): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
I have been looking for a solution for 3 days. I am an absolute newbie in programming / android, so this may just be a mistake, but I cannot find it.