开发者

How do you get the members of a contact group?

I have the ID of a contact group, and I'd like to list its members. Here's the code I'm tr开发者_如何转开发ying:

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 line starting result +=. Can anyone tell me what I'm doing wrong, or suggest a better way to get the same information?


Try this code snippet

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());
}


Cursor.getColumnIndex(String column) returns -1 when the column does not exist, and that is causing Cursor.getString(int colidx) to throw the exception.

I'd start testing by passing null for the third argument of the query call to see if you get a valid Cursor from the call.

If you don't get a valid Cursor, then I'd check to make sure that Data.CONTENT_URI is the right CONTENT_URI to call. It's hard to tell what the fully qualified path is without seeing your imports. (Edit: It looks like ContactsContract.Data.CONTENT_URI must be the constant there.)

If you do get a valid Cursor, then there might be an issue with that third argument.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜