How do I get the _count in my content provider?

戏子无情 提交于 2019-11-28 18:36:15
Will

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

saurabh

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.

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);
cesards

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!