How do I get the _count in my content provider?

pupeno picture pupeno · Jan 22, 2009 · Viewed 15.2k times · Source

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.

Answer

saurabh picture saurabh · May 9, 2011

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.