Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY with CursorLoader

How do I define a GROUP BY query for my CursorLoader?

The two constructors for a CursorLoader I see take either a single Context or a Context, Uri, projection, selection, selectionArgs and sortOrder.

But no groupBy.

(I'm using the support package for a Android 2.3 device)

like image 721
dbm Avatar asked May 14 '12 09:05

dbm


3 Answers

Not really...

You can define a specific URI to your specific GROUP BY clause.

For example, if you have a table mPersonTable, possibly grouped by gender, you can define the following URIs:

PERSON
PERSON/#
PERSON/GENDER

When querying, switch between your queries so you can add your group by parameter:

public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
   String groupBy = null;
   switch (mUriMatcher.match(uri)) {
      case PERSON_ID:
         ...
         break;
      case PERSON_GENDER:
         groupBy = GENDER_COLUMN;
      case PERSON:
        SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
        builder.setTables(mPersonTable);
        builder.setProjectionMap(mProjectionMap);
        return builder.query(db, projection, selection, selectionArgs, groupBy, having, sortOrder, limit);
      default:
         break;
   }
}

In fact, you could pass any sort of parameters to your query

Obs.: Use a UriMatcher to match the uri with your query implementation.

like image 165
JPMagalhaes Avatar answered Nov 20 '22 06:11

JPMagalhaes


You can add Group by with selection parameter

new CursorLoader(context,URI,
                        projection,
                                selection+") GROUP BY (coloum_name",
                        null,null);
like image 36
Gaurav Avatar answered Nov 20 '22 07:11

Gaurav


Apparently (and this is a bit embarrassing) the very first line in the documentation clearly states that the CursorLoader queries the ContentResolver to retrieve the Cursor. While the ContentResolver doesn't expose any means to GROUP BY there is, hence, no way the CursorLoader could expose such functionality either.

So the apparent answer to my very own question is: You can't!

like image 4
dbm Avatar answered Nov 20 '22 06:11

dbm