获取具有相同位置的数据并在TextView中显示它

时间:2016-02-17 12:06:33

标签: android mysql

我实际上有2个问题。我正在做这个用户输入日志的Android应用程序。在布局中,我有按地点分组的列表,我需要显示该地点的所有日志的计数。 这是我的地方分组代码

public ArrayList<Logs> getAllLogsGroupedByPlace() {
        ArrayList<Logs> logByPlaceList = new ArrayList<Logs>();
        String selectQuery = "SELECT * FROM " + TABLE_LOGS + " GROUP BY " + KEY_PLACE;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Logs log = new Logs();
                log.setId(cursor.getLong(0));
                log.setCreatedAt(cursor.getString(1));
                log.setPlace(cursor.getString(2));
                logByPlaceList.add(log);
            }while (cursor.moveToNext());
        }
        return logByPlaceList;
    }

这是我按地点计算日志的代码

public int getLogsCountPlace() {
        String countQuery = "SELECT * FROM " + TABLE_LOGS + " WHERE " + KEY_PLACE + "=" + KEY_PLACE;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        return cursor.getCount();
    }

所以我的问题是如何正确计算按地点分组的日志,然后将它们显示在我的列表textview中?

1 个答案:

答案 0 :(得分:0)

您应该更改getLogsCountPlace方法。

public Map<String,Integer> getLogsCountPlace() {
        String countQuery = "SELECT COUNT(*), " + KEY_PLACE + " FROM " + TABLE_LOGS + " GROUP BY " + KEY_PLACE;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        //// The cursor will return 2 columns, the first column will have the count of each place and the second column will have the place name. You could store the counts in a Map, having the place as the key and the count as the value.
        cursor.close();
    }