我的Class中有一个ListView,它将显示数据库表中每个类别的列表。在该列表视图中,我分别有三个TextViews,ROWID CategoryName和CategoryCount:
private void populateCategoryList() {
DatabaseHandler db = new DatabaseHandler(this);
TextView tvCategoryItem = (TextView) findViewById(R.id.tvCategoryItem);
TextView tvCatID = (TextView) findViewById(R.id.tvCatID);
TextView tvCatCount = (TextView) findViewById(R.id.tvCatCount);
Cursor cursor = db.getCategories();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
// startManagingCursor(cursor); //TODO Turned off because on back from contact details made a closed cursor error
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[] { db.KEY_ROWID, db.KEY_CATEGORY };
int[] toViewIDs = new int[] { R.id.tvCatID, R.id.tvCategoryItem };
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, // Context
R.layout.item_categorylist, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
/****** COUNT CODE ******/
// tvCatCount = (db.countCategory(category));
// Set the adapter for the list view
lvCategories = (ListView) findViewById(R.id.lvCategories);
lvCategories.setAdapter(myCursorAdapter);
db.close();
您可以在上面的toFields中看到我还没有为计数设置字段。我将使用tvCatCount。问题是,我如何以及在何处插入计数代码。在这种情况下计数?我认为countCategory需要是一个for循环,它应该获取该行的当前类别条目的id,调用db.countCategory并且tehn将TextView中的值设置为返回的结果?
这是db.countCategory代码:
public int countCategory(category){
SQLiteDatabase db = this.getWritableDatabase();
String[] categoryColumns = new String[] { KEY_ROWID, KEY_CATEGORY };
Cursor c = db.query(CATEGORY_TABLE, null, null, null, KEY_CATEGORY + "=" + category, null, null);
int result = c.getCount();
c.close();
Log.i("DATABASE", "Category Count for id " + id + "is " + result);
return result;
}
应该计算表中的每个条目等于“id”的值。这段代码已在其他地方使用了,所以我并不太担心,但要计算列表视图中的每一行,这是一种不同的动物。
答案 0 :(得分:0)
要显示每个类别的费用计数,您需要一个包含以下列的表格:
_id | CategoryName | Count
要计算此值,您必须将categories表连接到expense表,并使用GROUP BY为每个不同的类别值获取一个输出行:
SELECT Category.rowid AS _id,
Category.Name,
COUNT(*) AS NumberOfExpenses
FROM Category
JOIN Expenses ON Category.rowid = Expenses.CategoryID
GROUP BY Category.rowid