How do you get contact group members?

I have a contact group identifier, and I would like to list its members. Here is the code I'm trying:

String[] projection = new String[]{ ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID }; Cursor contacts = getContentResolver().query( Data.CONTENT_URI, projection, ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=" + gid, null, null ); String result = ""; do { result += contacts.getString(contacts.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID)) + " "; } while (contacts.moveToNext()); 

But this throws an exception:

 03-24 17:11:33.097: ERROR/AndroidRuntime(10730): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 2 ... 03-24 17:11:33.097: ERROR/AndroidRuntime(10730): at myapp.MultiSend$1.onItemClick(MultiSend.java:83) 

which is the beginning of the line result += . Can someone tell me what I'm doing wrong, or suggest a better way to get the same information?

+4
source share
2 answers

Try this piece of code, hope it helps

 String[] projection = new String[]{ ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID }; Cursor contacts = getContentResolver().query( Data.CONTENT_URI, projection, ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=" + gid, null, null ); startManagingCursor(contacts); String result = ""; if (contacts.moveToFirst()) { do { try { result += contacts.getString(contacts.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID)) + " "; } catch (Exception ex) { ex.printStackTrace(); } } while (contacts.moveToNext()); } 
+6
source

Cursor.getColumnIndex(String column) returns -1 when the column does not exist, and this causes Cursor.getString (int colidx) to throw an exception.

I would start testing by passing null for the third argument of the query request to find out if you have a valid Cursor from the call.

If you do not get a valid Cursor, I would check that Data.CONTENT_URI was the correct CONTENT_URI for the call. It is hard to say that this is the full path without seeing your import. (Edit: it looks like ContactsContract.Data.CONTENT_URI should be a constant.)

If you get a valid Cursor, then there may be a problem with this third argument.

0
source

Source: https://habr.com/ru/post/1345133/


All Articles