Android ContentProvider / SQLiteDatabase查询COUNT(*)

时间:2013-12-21 15:29:49

标签: android sql sqlite count android-contentprovider

我想检查一下我的桌子是否为空:

Uri uri = Uri.withAppendedPath(BASE_URI, "account");
Cursor countCursor = getContentResolver().query(uri, new String[] {"COUNT(*) AS COUNT_TABLE"}, null, null, null);

以下是我的内容提供商查询:

public synchronized Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    int uriType = sURIMatcher.match(uri);
    SQLiteDatabase database = dbHelper.getReadableDatabase();
    Cursor cursor = null;
    switch (uriType) {
    case ACCOUNT:
        checkColumns(projection, ACCOUNT);
        cursor = database.query(TableAccount.TABLE_ACCOUNT, projection, selection, selectionArgs, null, null, sortOrder);
        break;
    case INPUT:
        checkColumns(projection, INPUT);
        cursor = database.query(TableInput.TABLE_INPUT, projection, selection, selectionArgs, null, null, sortOrder);
        break;
    case OUTPUT:
        checkColumns(projection, OUTPUT);
        cursor = database.query(TableOutput.TABLE_OUTPUT, projection, selection, selectionArgs, null, null, sortOrder);
        break;
    default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    cursor.setNotificationUri(getContext().getContentResolver(), uri);
    return cursor;
}

但每次我收到此错误:

  

IllegalArgumentException:投影中的未知列

我不想使用rawQuerry

1 个答案:

答案 0 :(得分:0)

尝试使用此方法获取sqlite数据库的计数。我还添加了一些where子句样本供您参考。随意修改它:

    public int getCount(String param1, String param2){
        SQLiteDatabase db = this.getReadableDatabase();
        long count;
        count = DatabaseUtils.queryNumEntries(db, "TABLE_NAME",
                "param1=? AND param2=?", new String[]{param1, param2});

        db.close();
        return count;
    }