我在使用带有SUM的SQL查询时遇到了问题.我在列表视图中显示日期和克数.如果没有SUM,它会显示日期和克数,但如果一个日期有多个条目,则它不会增加克数.当我在sqlite数据库浏览器中测试时,SQL查询能够正常工作.以下是我的一些代码:
//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;
}
我也尝试过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;
}
如何输出查询结果:
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();
我认为logcat中显示的错误之一是解决方案的关键:
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)
我一直在寻找解决方案3天了.我是编程/ android的绝对初学者,所以它可能只是一个不起眼的错误,但我似乎无法找到它.
最佳答案 最后我可以回答我自己的问题,我起初因为限制而无法:)
看起来我设法解决了它.在有人在这里发布答案之后我找到了答案,但由于某种原因他删除了答案,所以我的回复评论也被删除了.结果我需要将查询更改为:
SELECT _id,date,sum(gram)as gram,FROM nutvalues GROUP BY date
所以这是因为我没有’as gram’部分.
感谢所有回复!