Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GROUP BY with CursorLoader - Android

I'm trying to get all Contacts from ContactsContract.CommonDataKinds.Email.CONTENT_URItable

grouped by their ContactID and Name using CursorLoader.

So for example, if contact have 2 emails, I will get only one row regarding this contact.

Basically, it should go like that:

SELECT ContactID, Name
FROM Table
GROUP BY ContactID, Name

My code:

String filter = ContactsContract.CommonDataKinds.Email.DATA + " NOT LIKE '')) 
GROUP BY ((" + ContactsContract.CommonDataKinds.Email.CONTACT_ID + ", display_name";

final static String[] PROJECTION =
{
   Utils.hasHoneycomb() ? Contacts.DISPLAY_NAME_PRIMARY : Contacts.DISPLAY_NAME,
   ContactsContract.CommonDataKinds.Email.CONTACT_ID,
};

return new CursorLoader(getActivity(),
                    ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    ContactsQuery.PROJECTION,
                    filter,
                    null,
                    ContactsQuery.SORT_ORDER);

I'm getting next SQLite error:

"Caused by: android.database.sqlite.SQLiteException: near ",": syntax error: , while compiling: SELECT DISTINCT display_name, contact_id FROM view_data_restricted data WHERE (1 AND mimetype_id = 1) AND ((data1 NOT LIKE '')) GROUP BY ((contact_id, display_name)) ORDER BY sort_key"

So this is my query:

SELECT DISTINCT display_name, contact_id FROM view_data_restricted data 
WHERE (1 AND mimetype_id = 1) AND ((data1 NOT LIKE '')) 
GROUP BY ((contact_id, display_name)) ORDER BY sort_key
  1. "DISTINCT" added by the cursorLoader. Why?
  2. I know there are multiple "(" / ")" signs, It's the best way I found to handle the adding of the "GROUP_BY". any other ideas will help.
  3. I can't find the problem near "," as the error said.
like image 797
David Avatar asked Jun 12 '26 15:06

David


1 Answers

the problem lies in how CursorLoader construct your query statement.

According to this:

The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used.

Unfortunately, you can't achieve this if you are passing Selection, Projection and SortOrder as parameters. There's no place to "hack" in the "Group By" statement..

like image 72
xialin Avatar answered Jun 14 '26 05:06

xialin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!