2011-03-24 23 views
4

我有联系人组的ID,我想列出其成员。下面是我想要的代码:你如何获得联系人组的成员?

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

但是,这将引发异常:

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) 

这是开始result +=行。任何人都可以告诉我我做错了什么,或者建议更好的方式来获得相同的信息?

回答

6

试试这个代码片段,希望它有助于

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

} 
+0

我很高兴它帮助:) – 2011-03-28 12:41:03

+0

'startManagingCursor()'现在已经过时,看到http://www.androiddesignpatterns.com/2012/07/装载机和-loadermanager-background.html – 2012-11-06 22:14:42

0

Cursor.getColumnIndex(String column)当列不存在时返回-1,并且导致Cursor.getString(int colidx)抛出异常。

我会开始测试,通过为查询调用的第三个参数传递null来查看您是否从调用中获得有效的游标。

如果你没有得到一个有效的游标,那么我会检查以确保Data.CONTENT_URI是正确的CONTENT_URI调用。如果没有看到您的导入,很难说出完全合格的路径。 (编辑:它看起来像ContactsContract.Data.CONTENT_URI必须是那里的常量。)

如果您确实得到一个有效的光标,那么可能有与第三个参数有关的问题。

相关问题