Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top