Search code examples
javaandroidcontacts

how to add a contact to a group android


I have following code to add contact to a group into android's contact app / people app, it does add the group but not the contact in that group, what am i missing ? I am adding contact successfully also creating group, i do get the ids of both the things , i m using following code to associate the contact with the group but its not working , group is always empty.

 public Uri addToGroup(long personId, long groupId) {

    ContentValues values = new ContentValues();
    values.put(ContactsContract.CommonDataKinds.GroupMembership.RAW_CONTACT_ID,
            personId);
    values.put(
            ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID,
            groupId);
    values
            .put(
                    ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE,
                    ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE);

    return this.getActivity().getContentResolver().insert(
            ContactsContract.Data.CONTENT_URI, values);

}

****update ***** Another thing i found is this group which i created doesn't get sync with google , probably thats the reason contacts aren't getting added.


Solution

  • Finally could add a contact to group, this is what was required, create a contact that syncs with google account (mandatory), second create a group that can sync to default sync service and then add contact the way i am adding in above code.

    if you are curious in knowing how to create group that can sync, here it is

    public String createGroup(String name) {
    
        String[] GROUP_PROJECTION = new String[] { ContactsContract.Groups._ID,     ContactsContract.Groups.TITLE };
    
        try {
            ContentValues groupValues = null;
            ContentResolver cr = this.getContentResolver();
            groupValues = new ContentValues();
            groupValues.put(ContactsContract.Groups.TITLE, name);
            groupValues.put(ContactsContract.Groups.SHOULD_SYNC,true);
            cr.insert(ContactsContract.Groups.CONTENT_URI, groupValues);
    
        }
        catch(Exception e){
            Log.d("########### Exception :",""+e.getMessage());
            return "1";
        }
    
        String groupID = null;
        Cursor getGroupID_Cursor = null;
        getGroupID_Cursor = this.getContentResolver().query(ContactsContract.Groups.CONTENT_URI,  GROUP_PROJECTION, ContactsContract.Groups.TITLE+ "=?", new String[]{name}, null);
    
        getGroupID_Cursor.moveToFirst();
        groupID = (getGroupID_Cursor.getString(getGroupID_Cursor.getColumnIndex("_id")));
    
        return groupID;
    
    
    }