How do I get the _count in my content provider?

2019-01-22 02:02发布

What should I do to get my content provider to return the _count column with the count of records? The documentation says it is automatic, but maybe it's only taking about some built-in content provider. Running a query to the database seems not to return it.

4条回答
叛逆
2楼-- · 2019-01-22 02:05

If you are using contentProvider then you have to do it like count(*) AS count.

If you use cursor.getCount(), that would not be as efficient as the above approach. With cursor.getCount() you are fetching all the records just to get counts. The entire code should look like following -

 Cursor countCursor = getContentResolver().query(CONTENT_URI,
                new String[] {"count(*) AS count"},
                null,
                null,
                null);

        countCursor.moveToFirst();
        int count = countCursor.getInt(0);

The reason why this works is because android needs a column name to be defined.

查看更多
Anthone
3楼-- · 2019-01-22 02:11

With cursor.getCount() you can not assure that it returns the real number of items returned. There are much better ways:

1- If you are using Content Providers, you can do a query and use the Column (_COUNT) included in BaseColumns for your projection

@Override
public Cursor query(SQLiteDatabase db, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    ...

    projection = new String[] {
        ContentContract.NotificationCursor.NotificationColumns._COUNT,
    };

    ...

    Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, groupBy, having, sortOrder);
    return cursor;
}

2- To do a rawQuery using SELECT COUNT(*) as @saurabh says in his response.

查看更多
Emotional °昔
4楼-- · 2019-01-22 02:13

If you are using ContentProvider.query() a Cursor is returned. Call Cursor.getCount() to get a count of records in the returned cursor.

查看更多
何必那么认真
5楼-- · 2019-01-22 02:13

I had a similiar problem and found this worked for me. In the example below I wanted to get the count of images from the MediaStore provider.

        final String[] imageCountProjection = new String[] {
                "count(" + MediaStore.Images.ImageColumns._ID + ")",
        };

        Cursor countCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                imageCountProjection,
                null,
                null,
                null);

        countCursor.moveToFirst();
        int existingImageCount = countCursor.getInt(0);
查看更多
登录 后发表回答