2011-03-24 22 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必須是那裏的常量。)

如果您確實得到一個有效的光標,那麼可能有與第三個參數有關的問題。

相關問題