如何在Android中按组名获取联系人列表?

时间:2014-03-12 08:23:05

标签: android addressbook

我想通过群组名称获取Android设备本地地址簿中的所有联系人。比如“家庭”,“朋友”,“工作”......就像Android设备中的地址簿一样。

这是我的代码:

 public void getAllContactsByGroup(ContentResolver cr) {

        String a  = "Friends";  
        Uri CONTENT_URI_GR = ContactsContract.Groups.CONTENT_URI;
        String GR_ID = ContactsContract.Groups._ID;
        String GR_NAME = ContactsContract.Groups.TITLE;

        Cursor cursor = getContentResolver().query(CONTENT_URI_GR, 
                null, GR_NAME + "=?", new String[] { a }, null);

        while (cursor.moveToNext())
        {
            Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
            String _ID = ContactsContract.Contacts._ID;
            String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;

            Cursor phones = cr.query(CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");

            countContact = phones.getCount();
            while (phones.moveToNext())
            {
                contact_id = phones.getString(phones.getColumnIndex(_ID));
                String name = phones.getString(phones.getColumnIndex(DISPLAY_NAME));

                name1.add(name);
                _idd.add(contact_id);
            }

            phones.close();
        }
        cursor.close();
     }

我尝试在地址簿的“好友”群组中进行所有联系,但它会获得所有群组的所有联系人。

1 个答案:

答案 0 :(得分:0)

尝试

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Cursor cur = getContacts();

    ListView lv = getListView();

   String[] fields = new String[] {ContactsContract.Data.DISPLAY_NAME};

   SimpleCursorAdapter adapter = 
            new SimpleCursorAdapter(this, 
                                    R.layout.main,
                                    cur,
                                    fields,
                                    new int[] {R.id.txtbox});
      lv.setAdapter(adapter);         
}    

private Cursor getContacts() {  
    // Run query     
    Uri uri = ContactsContract.Contacts.CONTENT_URI;

    String[] projection = 
            new String[]{ ContactsContract.Contacts._ID,
                          ContactsContract.Contacts.DISPLAY_NAME }; 
        String selection = null;
        String[] selectionArgs = null;  
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + 
            " COLLATE LOCALIZED ASC";  
        return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}