Search code examples
androidsqlcountandroid-cursor

Android Cursor Query Count


I'm developing a small application that reads data from a database and displys it in a few custom listview layouts.

I got all my ducks in a row but have one issue where I can't wrap my mind around which is preforming a count within the cursor query

Here is a simple example of my code

private static final String fields[] = { "CarYear","CarMake","CarModel","CarInfo", BaseColumns._ID }; //BaseColumns._ID

And the query itself

                Cursor data = database.query("Car060", fields, null, null, null, null,null);

So the big question is how can I either preform a total count per maker or just a total count.

Thanks for any assistance

Ended up using a RawQuery

Cursor Count = database.rawQuery("SELECT COUNT(DISTINCT People) as NumberOfPeople FROM WhatEverDB", null);


Solution

  • You can use Cursor.getCount() to get the total number of rows returned by the cursor.

    To count individual 'makers' you can either iterate over the cursor, and count them yourself, or use another query to issue COUNT SQL to the server and retrieve the counts from there.

    As you're already fetching this data for use in a ListView, I'd guess that the former is more efficient.