Want to create a new group in contacts programmatically

风流意气都作罢 提交于 2019-12-03 00:40:15

i found the answer.i found in two ways but i dont know which is correct or best way to use.i am sharing those here..

its simple way like adding contact,

ContentValues groupValues;
create group()
{
 ContentResolver cr = this.getContentResolver();
 groupValues = new ContentValues();
 groupValues.put(ContactsContract.Groups.TITLE, "MyContactGroup");
 cr.insert(ContactsContract.Groups.CONTENT_URI, groupValues);
}

Another method using ContentProviderOperation

 private void createGroup() {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    ops.add(ContentProviderOperation
            .newInsert(ContactsContract.Groups.CONTENT_URI)
            .withValue(ContactsContract.Groups.TITLE, "SRI").build());
    try {

        getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

    } catch (Exception e) {
        Log.e("Error", e.toString());
    }

}

Thanks

Why are you specifying group ID with groupValues.put(android.provider.Contacts.GroupMembership.GROUP_ID, 4); Its androids job to determined the group ID, you cant specify it because you don't know whether this id is already taken or not.

adithi's answer is enough for Android 4.2.2, in which the name of Contacts manager application is "Contacts" , but the group created by that code will not show on Android 4.4,6 in which the name of Contacts manager application is "People".

The group would show up after adding the account type/name information while insertion happens.

private void createGroup() {

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        ops.add(ContentProviderOperation
                .newInsert(ContactsContract.Groups.CONTENT_URI)
                .withValue(
                        ContactsContract.Groups.TITLE,
                        Constants.CC_CONTACT_GROUP_TITLE)
                .withValue(
                        ContactsContract.Groups.ACCOUNT_TYPE,
                        Constants.CC_CONTACT_GROUP_ACCOUNT_TYPE)
                .withValue(
                        ContactsContract.Groups.ACCOUNT_NAME,
                        Constants.CC_CONTACT_GROUP_ACCOUNT_NAME)
                .build());
    try {

        getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

    } catch (Exception e) {
        Log.e("Error", e.toString());
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!