How To Add Contact In Android Programmatically

This article will give you an example about steps to create android contact programmatically and how to insert each android contact field into contact data table. When click the add contact button, it will generate a contact and insert it into android contact tables.

how to add contact in android programmatically example release

1. Android Contacts Read Write Permissions.

When add android contact for the first time, because the action need below android runtime permissions, so it will popup a confirm dialog which let you to allow the action.

Below permissions need to be declared in AndroidManifest.xml file. You can read article Android Marshmallow Runtime Permission Example to learn more about android runtime permission.

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />

2. Add Android Contact Steps.

Before continue reading, if you do not know the android contact database structure, please read article Android Contacts Database Structure.

If you do not know what the columns data means for android contact data table. You can read article Android Contacts Fields, Data Table Columns And Data Mimetype Explain.

Below is the steps to create an android contact.

  1. Create a contact group ( insert into groups table.)
  2. Create a contact ( insert into contacts and raw_contacts table.)
  3. Insert below contact field info in data table, one field info one raw, and the data table mimetype_id column decides what the row data means, it also decides which data column is used to save what data.
  4. Inserted contact info field include group id, multiple contact address, organization, multiple email address, nickname, note, multiple phone, multiple website, multiple im, postal address, identity and photo.
    android contact table data

3. Add Android Contact Example Source Code.

3.1 Add Contact Code.

// Create a new contact and add it to android contact address book.
private void addContact()
{
    // Create a new fake contact first.
    ContactDTO contactDto = generateRandomContactDTO(-1);

    // First get contentresolver object.
    ContentResolver contentResolver = getContentResolver();

    String groupTitle = "Workmate";

    String groupNotes = "Company workmates contacts";

    long groupId = getExistGroup(contentResolver, groupTitle);

    // Group do not exist.
    if(groupId == -1) {
        // Create a new group
        groupId = insertGroup(contentResolver, groupTitle, groupNotes);
    }

    // Create a new contact.
    long rawContactId = insertContact(contentResolver, contactDto);

    // Set group id.
    contactDto.setGroupId(groupId);
    // Contact id and raw contact id has same value.
    contactDto.setContactId(rawContactId);
    contactDto.setRawContactId(rawContactId);

    // Insert contact group membership data ( group id ).
    insertGroupId(contentResolver, contactDto.getGroupId(), contactDto.getRawContactId());

    // Insert contact address list data.
    insertListData(contentResolver, ContactsContract.Data.CONTENT_URI,
            contactDto.getRawContactId(),
            ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE,
            ContactsContract.CommonDataKinds.SipAddress.TYPE,
            ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS,
            contactDto.getAddressList());

    // Insert organization data.
    insertOrganization(contentResolver, contactDto);

    // Insert contact display, given and family name.
    insertName(contentResolver, contactDto);

    /* Insert contact email list data, Content uri do not use ContactsContract.CommonDataKinds.Email.CONTENT_URI
     * Otherwise it will throw error java.lang.UnsupportedOperationException: URI: content://com.android.contacts/data/emails */
    insertListData(contentResolver, ContactsContract.Data.CONTENT_URI,
            contactDto.getRawContactId(),
            ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
            ContactsContract.CommonDataKinds.Email.TYPE,
            ContactsContract.CommonDataKinds.Email.ADDRESS,
            contactDto.getEmailList());

    // Insert contact nickname.
    insertNickName(contentResolver, contactDto);

    // Insert contact note.
    insertNote(contentResolver, contactDto);

    /* Insert contact phone list data, Content uri do not use ContactsContract.CommonDataKinds.Phone.CONTENT_URI
     * Otherwise it will throw error java.lang.UnsupportedOperationException: URI: content://com.android.contacts/data/phones */
    insertListData(contentResolver, ContactsContract.Data.CONTENT_URI,
            contactDto.getRawContactId(),
            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
            ContactsContract.CommonDataKinds.Phone.TYPE,
            ContactsContract.CommonDataKinds.Phone.NUMBER,
            contactDto.getPhoneList());

    // Insert contact website list.
    insertListData(contentResolver, ContactsContract.Data.CONTENT_URI,
            contactDto.getRawContactId(),
            ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE,
            ContactsContract.CommonDataKinds.Website.TYPE,
            ContactsContract.CommonDataKinds.Website.URL,
            contactDto.getWebsiteList());

    // Insert contact im list.
    insertListData(contentResolver, ContactsContract.Data.CONTENT_URI,
            contactDto.getRawContactId(),
            ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE,
            ContactsContract.CommonDataKinds.Im.PROTOCOL,
            ContactsContract.CommonDataKinds.Im.DATA,
            contactDto.getImList());

    // Insert contact post address
    insertPostalAddress(contentResolver, contactDto);

    // Insert identity
    insertIdentity(contentResolver, contactDto);

    // Insert photo
    insertPhoto(contentResolver, contactDto);
}

3.2 Generate Random Data Contact DTO code.

First need to generate a ContactDTO object with random generated contact info.

/* Generate a contact dto object.
   Each dto object field value has a uuid string .
   */
private ContactDTO generateRandomContactDTO(long currentSystemTime)
{
    ContactDTO contactDto = new ContactDTO();

    String uuidStr = "";

    if(currentSystemTime!=-1) {
       uuidStr += "_" + currentSystemTime;
    }

    //**************************************************************
    // Create contact address list.
    List<DataDTO> addressList = new ArrayList<DataDTO>();

    // Create home address.
    DataDTO homeAddressDto = new DataDTO();
    homeAddressDto.setDataType(ContactsContract.CommonDataKinds.SipAddress.TYPE_HOME);
    homeAddressDto.setDataValue("3122 Camden Street"+uuidStr);
    addressList.add(homeAddressDto);

    // Create work address.
    DataDTO workAddressDto = new DataDTO();
    workAddressDto.setDataType(ContactsContract.CommonDataKinds.SipAddress.TYPE_WORK);
    workAddressDto.setDataValue("3819 Watson Street"+uuidStr);
    addressList.add(workAddressDto);

    // Add address list.
    contactDto.setAddressList(addressList);

    //***************************************************************
    // Below is contact organization related info.

    // Set company
    contactDto.setCompany("IBM"+uuidStr);
    // Set department
    contactDto.setDepartment("Development Team"+uuidStr);
    // Set title
    contactDto.setTitle("Senior Software Engineer"+uuidStr);
    // Set job description
    contactDto.setJobDescription("Develop features use java."+uuidStr);
    // Set office location.
    contactDto.setOfficeLocation("Mountain View"+uuidStr);

    //***************************************************************
    // Create email address list.
    List<DataDTO> emailList = new ArrayList<DataDTO>();

    // Create work email.
    DataDTO workEmailDto = new DataDTO();
    workEmailDto.setDataType(ContactsContract.CommonDataKinds.Email.TYPE_WORK);
    workEmailDto.setDataValue("jack"+uuidStr+"@dev2qa.com");
    emailList.add(workEmailDto);

    // Create home email.
    DataDTO homeEmailDto = new DataDTO();
    homeEmailDto.setDataType(ContactsContract.CommonDataKinds.Email.TYPE_HOME);
    homeEmailDto.setDataValue("jack"+uuidStr+"@gmail.com");
    emailList.add(homeEmailDto);

    // Add email list.
    contactDto.setEmailList(emailList);

    //***************************************************************
    // Below is structured name related info.

    contactDto.setDisplayName("Jack"+uuidStr);

    contactDto.setGivenName("Bill"+uuidStr);

    contactDto.setFamilyName("Trump"+uuidStr);

    //**************************************************************
    // Contact nick name related info.

    contactDto.setNickName("FlashMan"+uuidStr);

    //**************************************************************
    // Contact note related info.
    contactDto.setNote("dev2qa.com senior engineer"+uuidStr);

    //**************************************************************
    // Im related info
    List<DataDTO> imList = new ArrayList<DataDTO>();

    DataDTO qqDto = new DataDTO();
    qqDto.setDataType(ContactsContract.CommonDataKinds.Im.PROTOCOL_QQ);
    qqDto.setDataValue("QQ_888" + uuidStr);
    imList.add(qqDto);

    DataDTO icqDto = new DataDTO();
    icqDto.setDataType(ContactsContract.CommonDataKinds.Im.PROTOCOL_ICQ);
    icqDto.setDataValue("ICQ_666" + uuidStr);
    imList.add(icqDto);

    DataDTO skypeDto = new DataDTO();
    skypeDto.setDataType(ContactsContract.CommonDataKinds.Im.PROTOCOL_SKYPE);
    skypeDto.setDataValue("SKYPE_968" + uuidStr);
    imList.add(skypeDto);

    contactDto.setImList(imList);

    //***************************************************************
    // Create phone list.
    List<DataDTO> phoneList = new ArrayList<DataDTO>();

    // Create mobile phone.
    DataDTO mobilePhone = new DataDTO();
    mobilePhone.setDataType(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
    mobilePhone.setDataValue("13901111118"+uuidStr);
    phoneList.add(mobilePhone);

    // Create work mobile phone.
    DataDTO workMobilePhone = new DataDTO();
    workMobilePhone.setDataType(ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE);
    workMobilePhone.setDataValue("13801234567"+uuidStr);
    phoneList.add(workMobilePhone);

    // Create home phone.
    DataDTO homePhone = new DataDTO();
    homePhone.setDataType(ContactsContract.CommonDataKinds.Phone.TYPE_HOME);
    homePhone.setDataValue("010-123456789"+uuidStr);
    phoneList.add(homePhone);

    contactDto.setPhoneList(phoneList);

    //***************************************************************
    // Create website list
    List<DataDTO> websiteList = new ArrayList<DataDTO>();

    // Create work website dto.
    DataDTO workWebsiteDto = new DataDTO();
    workWebsiteDto.setDataType(ContactsContract.CommonDataKinds.Website.TYPE_WORK);
    workWebsiteDto.setDataValue(uuidStr+".dev2qa.com");
    websiteList.add(workWebsiteDto);

    // Create blog website dto.
    DataDTO blogWebsiteDto = new DataDTO();
    blogWebsiteDto.setDataType(ContactsContract.CommonDataKinds.Website.TYPE_BLOG);
    blogWebsiteDto.setDataValue(uuidStr+".blog.dev2qa.com");
    websiteList.add(blogWebsiteDto);

    contactDto.setWebsiteList(websiteList);

    //**************************************************************
    // Set postal related info.
    contactDto.setCountry("USA"+uuidStr);
    contactDto.setCity("Chicago"+uuidStr);
    contactDto.setRegion("Washington DC"+uuidStr);
    contactDto.setStreet("2260 West Drive"+uuidStr);
    contactDto.setPostCode("60606"+uuidStr);
    contactDto.setPostType(ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME);

    //**************************************************************
    // Set identity info.
    contactDto.setIdentity("347-80-XXXX"+uuidStr);
    contactDto.setNamespace("SSN");

    //**************************************************************
    // Set photo info.
    contactDto.setPhoto(uuidStr+".png");
    contactDto.setPhotoFieldId(uuidStr);

    return contactDto;
}

3.3 Get Exist Group ID Method.

This method query the group id from the groups table use group title as query condition. If it exist then return group id otherwise return -1.

/*
*  Check whether the group exist of not.
*  Return exist group id or -1 if group is not exist.
* */
private long getExistGroup(ContentResolver contentResolver, String groupTitle)
{
    long ret = -1;

    String queryColumnArr[] = {ContactsContract.Groups._ID};

    StringBuffer whereClauseBuf = new StringBuffer();
    whereClauseBuf.append(ContactsContract.Groups.TITLE);
    whereClauseBuf.append("='");
    whereClauseBuf.append(groupTitle);
    whereClauseBuf.append("'");

    Cursor cursor = contentResolver.query(ContactsContract.Groups.CONTENT_URI, queryColumnArr, whereClauseBuf.toString(), null, null);
    if(cursor!=null)
    {
        if(cursor.getCount()>0)
        {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(ContactsContract.Groups._ID);
            ret = cursor.getLong(columnIndex);
        }
    }
    return ret;
}

3.4 Create New Contact Group Method.

Insert new contact group in groups table and return the newly created group id.

/*
*  Insert a new contact group.
*  Return newly created group id.
* */
private long insertGroup(ContentResolver contentResolver, String groupTitle, String groupNotes)
{
    // Insert a group in group table.
    ContentValues contentValues = new ContentValues();
    contentValues.put(ContactsContract.Groups.TITLE, groupTitle);
    contentValues.put(ContactsContract.Groups.NOTES, groupNotes);
    Uri groupUri = contentResolver.insert(ContactsContract.Groups.CONTENT_URI, contentValues);
    // Get the newly created raw contact id.
    long groupId = ContentUris.parseId(groupUri);

    return groupId;
}

3.5 Create New Contact Method.

This method will insert data into both contacts and raw_contacts table and return newly created contact table id.

/*
*  Insert a new empty contact.
*  Return newly created contact id.
* */
private long insertContact(ContentResolver contentResolver, ContactDTO contactDto)
{
    // Insert an empty contact in both contacts and raw_contacts table.
    // Return the system generated new contact and raw_contact id.
    // The id in contacts and raw_contacts table has same value.
    ContentValues contentValues = new ContentValues();
    contentValues.put(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY, contactDto.getDisplayName());
    contentValues.put(ContactsContract.RawContacts.DISPLAY_NAME_ALTERNATIVE, contactDto.getDisplayName());

    Uri rawContactUri = contentResolver.insert(ContactsContract.RawContacts.CONTENT_URI, contentValues);
    // Get the newly created raw contact id.
    long rawContactId = ContentUris.parseId(rawContactUri);
    return rawContactId;
}

3.6 Insert Contact Group Id In Data Table.

The row data mimetype is vnd.android.cursor.item/group_membership.

/* Insert contact belongs group id in data table. */
private void insertGroupId(ContentResolver contentResolver, long groupRowId, long rawContactId)
{
    ContentValues contentValues = new ContentValues();
    // Set raw contact id. Data table only has raw_contact_id.
    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);

    // Set mimetype first.
    contentValues.put(ContactsContract.CommonDataKinds.StructuredName.MIMETYPE, ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE);
    // Set contact belongs group id.
    contentValues.put(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID, groupRowId);

    // Insert to data table.
    contentResolver.insert(ContactsContract.Data.CONTENT_URI, contentValues);
}

3.7 Insert Multiple Address Info In Data Table.

Because one android contact can has multiple address info, such as home address, work address etc. So the address info is saved in a list object, and each row in data table represent one address.

READ :   How To Open Camera In Android Programmatically Using Intent

The row data mimetype is vnd.android.cursor.item/sip_address.

Please note for some contact field, the content provider uri should use  ContactsContract.Data.CONTENT_URI, otherwise it maybe throw error  java.lang.UnsupportedOperationException: URI:content://com.android.contacts/data/emailss like below picture.

android contact content provider unsupportedoperationexception error for email

// Insert contact address list data.
insertListData(contentResolver, ContactsContract.Data.CONTENT_URI,
        contactDto.getRawContactId(),
        ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE,
        ContactsContract.CommonDataKinds.SipAddress.TYPE,
        ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS,
        contactDto.getAddressList());
/*  Insert list DataDTO into data table.
 *  ContentResolver contentResolver : The content resolver object.
 *  Uri contentUri : Insert data uri. ( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, Email.CONTENT_URI etc.)
 *  long contactId : contacts table id.
 *  long rawContactId : raw_contacts table id. Same value with contacts table id.
 *  String mimeType : The inserted data mime type. ( ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, Phone.CONTENT_ITEM_TYPE etc. )
 *  String dataTypeColumnName : Data type column name.( ContactsContract.CommonDataKinds.Email.TYPE, Phone.TYPE etc.)
 *  String dataValueColumnName : Data value column name. ( ContactsContract.CommonDataKinds.Phone.NUMBER, Email.ADDRESS, Nickname.NAME etc)
 *   List<DataDTO> dataList : Data list, such as phone list, address list and email list etc.
* */
private void insertListData(ContentResolver contentResolver, Uri contentUri, long rawContactId, String mimeType, String dataTypeColumnName, String dataValueColumnName, List<DataDTO> dataList)
{
    if(dataList!=null) {

        ContentValues contentValues = new ContentValues();

        int size = dataList.size();

        for(int i=0;i<size;i++) {

            DataDTO dataDto = dataList.get(i);

            contentValues.clear();

            // Set raw contact id. Data table only has raw_contact_id.
            contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
            // Set data mimetype.
            contentValues.put(ContactsContract.Data.MIMETYPE, mimeType);
            // Set data type.
            contentValues.put(dataTypeColumnName, dataDto.getDataType());
            // Set data value.
            contentValues.put(dataValueColumnName, dataDto.getDataValue());

            contentResolver.insert(contentUri, contentValues);
        }
    }

}

3.8 Insert Multiple Email Info In Data Table.

Similar with 3.7 insert multiple address info. The row data mimetype is vnd.android.cursor.item/email_v2.

/* Insert contact email list data, Content uri do not use ContactsContract.CommonDataKinds.Email.CONTENT_URI
 * Otherwise it will throw error java.lang.UnsupportedOperationException: URI: content://com.android.contacts/data/emails */
insertListData(contentResolver, ContactsContract.Data.CONTENT_URI,
        contactDto.getRawContactId(),
        ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
        ContactsContract.CommonDataKinds.Email.TYPE,
        ContactsContract.CommonDataKinds.Email.ADDRESS,
        contactDto.getEmailList());

3.9 Insert Multiple Phone Info In Data Table.

Similar with 3.7 insert multiple address info. The row data mimetype is vnd.android.cursor.item/phone_v2.

/* Insert contact phone list data, Content uri do not use ContactsContract.CommonDataKinds.Phone.CONTENT_URI
 * Otherwise it will throw error java.lang.UnsupportedOperationException: URI: content://com.android.contacts/data/phones */
insertListData(contentResolver, ContactsContract.Data.CONTENT_URI,
        contactDto.getRawContactId(),
        ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
        ContactsContract.CommonDataKinds.Phone.TYPE,
        ContactsContract.CommonDataKinds.Phone.NUMBER,
        contactDto.getPhoneList());

3.10 Insert Multiple Website Info In Data Table.

Similar with 3.7 insert multiple address info. The row data mimetype is vnd.android.cursor.item/website.

// Insert contact website list.
insertListData(contentResolver, ContactsContract.Data.CONTENT_URI,
        contactDto.getRawContactId(),
        ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE,
        ContactsContract.CommonDataKinds.Website.TYPE,
        ContactsContract.CommonDataKinds.Website.URL,
        contactDto.getWebsiteList());

3.11 Insert Multiple Instant Messenger Info In Data Table.

Similar with 3.7 insert multiple address info. The row data mimetype is vnd.android.cursor.item/im.

// Insert contact im list.
insertListData(contentResolver, ContactsContract.Data.CONTENT_URI,
        contactDto.getRawContactId(),
        ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE,
        ContactsContract.CommonDataKinds.Im.PROTOCOL,
        ContactsContract.CommonDataKinds.Im.DATA,
        contactDto.getImList());

3.12 Insert Organization Info In Data Table.

The row data mimetype is vnd.android.cursor.item/organization.

/*  Insert organization info into data table.
 *  ContentResolver contentResolver : The content resolver object.
 *  ContactDTO contactDto : Contact dto contains all the insert data.
* */
private void insertOrganization(ContentResolver contentResolver, ContactDTO contactDto)
{
    if(contactDto!=null) {

        ContentValues contentValues = new ContentValues();

        // Set raw contact id. Data table only has raw_contact_id.
        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, contactDto.getRawContactId());
        // Set data mimetype.
        contentValues.put(ContactsContract.CommonDataKinds.Organization.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
        // Set company name.
        contentValues.put(ContactsContract.CommonDataKinds.Organization.COMPANY, contactDto.getCompany());
        // Set department.
        contentValues.put(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, contactDto.getDepartment());
        // Set title.
        contentValues.put(ContactsContract.CommonDataKinds.Organization.TITLE, contactDto.getTitle());
        // Set job description.
        contentValues.put(ContactsContract.CommonDataKinds.Organization.JOB_DESCRIPTION, contactDto.getJobDescription());
        // Set office location.
        contentValues.put(ContactsContract.CommonDataKinds.Organization.OFFICE_LOCATION, contactDto.getOfficeLocation());

        // Insert to data table.
        contentResolver.insert(ContactsContract.Data.CONTENT_URI, contentValues);
    }
}

3.12 Insert Structrued Name Info In Data Table.

The row data mimetype is vnd.android.cursor.item/name.

/*  Insert name info into data table.
 *  ContentResolver contentResolver : The content resolver object.
 *  ContactDTO contactDto : Contact dto contains all the insert data.
* */
private void insertName(ContentResolver contentResolver, ContactDTO contactDto)
{
    if(contactDto!=null) {

        ContentValues contentValues = new ContentValues();

        // Set raw contact id. Data table only has raw_contact_id.
        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, contactDto.getRawContactId());
        // Set data mimetype.
        contentValues.put(ContactsContract.CommonDataKinds.StructuredName.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        // Set display name.
        contentValues.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contactDto.getDisplayName());
        // Set given name.
        contentValues.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, contactDto.getGivenName());
        // Set family name.
        contentValues.put(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, contactDto.getFamilyName());
        // Insert to data table.
        contentResolver.insert(ContactsContract.Data.CONTENT_URI, contentValues);
    }
}

3.13 Insert NickName Info In Data Table.

The row data mimetype is vnd.android.cursor.item/nickname.

/*  Insert nick name info into data table.
 *  ContentResolver contentResolver : The content resolver object.
 *  ContactDTO contactDto : Contact dto contains all the insert data.
* */
private void insertNickName(ContentResolver contentResolver, ContactDTO contactDto)
{
    if(contactDto!=null) {

        ContentValues contentValues = new ContentValues();

        // Set raw contact id. Data table only has raw_contact_id.
        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, contactDto.getRawContactId());
        // Set data mimetype.
        contentValues.put(ContactsContract.CommonDataKinds.Nickname.MIMETYPE, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE);
        // Set display name.
        contentValues.put(ContactsContract.CommonDataKinds.Nickname.NAME, contactDto.getNickName());
        // Insert to data table.
        contentResolver.insert(ContactsContract.Data.CONTENT_URI, contentValues);
    }
}

3.14 Insert Note Info In Data Table.

The row data mimetype is vnd.android.cursor.item/note.

/*  Insert note info into data table.
 *  ContentResolver contentResolver : The content resolver object.
 *  ContactDTO contactDto : Contact dto contains all the insert data.
* */
private void insertNote(ContentResolver contentResolver, ContactDTO contactDto)
{
    if(contactDto!=null) {

        ContentValues contentValues = new ContentValues();

        // Set raw contact id. Data table only has raw_contact_id.
        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, contactDto.getRawContactId());
        // Set data mimetype.
        contentValues.put(ContactsContract.CommonDataKinds.Note.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE);
        // Set display name.
        contentValues.put(ContactsContract.CommonDataKinds.Note.NOTE, contactDto.getNote());
        // Insert to data table.
        contentResolver.insert(ContactsContract.Data.CONTENT_URI, contentValues);
    }
}

3.15 Insert Postal Address Info In Data Table.

The row data mimetype is vnd.android.cursor.item/postal-address_v2.

/* Insert contact postal address info in data table. */
private void insertPostalAddress(ContentResolver contentResolver, ContactDTO contactDto)
{
    ContentValues contentValues = new ContentValues();
    // Set raw contact id. Data table only has raw_contact_id.
    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, contactDto.getRawContactId());
    // Set mimetype first.
    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
    // Set country
    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, contactDto.getCountry());
    // Set city
    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY, contactDto.getCity());
    // Set region
    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION, contactDto.getRegion());
    // Set street
    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET, contactDto.getStreet());
    // Set postcode
    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, contactDto.getPostCode());
    // Set postcode
    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, contactDto.getPostType());

    /* Insert to data table. Do not use uri ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
       Otherwise it will throw error java.lang.UnsupportedOperationException: URI: content://com.android.contacts/data/postals*/
    contentResolver.insert(ContactsContract.Data.CONTENT_URI, contentValues);
}

3.16 Insert Identity Info In Data Table.

The row data mimetype is vnd.android.cursor.item/identity.

/* Insert contact identity info in data table. */
private void insertIdentity(ContentResolver contentResolver, ContactDTO contactDto)
{
    ContentValues contentValues = new ContentValues();
    // Set raw contact id. Data table only has raw_contact_id.
    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, contactDto.getRawContactId());
    // Set mimetype first.
    contentValues.put(ContactsContract.CommonDataKinds.Identity.MIMETYPE, ContactsContract.CommonDataKinds.Identity.CONTENT_ITEM_TYPE);
    // Set identity
    contentValues.put(ContactsContract.CommonDataKinds.Identity.IDENTITY, contactDto.getIdentity());
    // Set namespace
    contentValues.put(ContactsContract.CommonDataKinds.Identity.NAMESPACE, contactDto.getNamespace());

    // Insert to data table.
    contentResolver.insert(ContactsContract.Data.CONTENT_URI, contentValues);
}

3.17 Insert Photo Info In Data Table.

The row data mimetype is vnd.android.cursor.item/photo.

/* Insert contact photo info in data table. */
private void insertPhoto(ContentResolver contentResolver, ContactDTO contactDto)
{
    ContentValues contentValues = new ContentValues();
    // Set raw contact id. Data table only has raw_contact_id.
    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, contactDto.getRawContactId());
    // Set mimetype first.
    contentValues.put(ContactsContract.CommonDataKinds.Photo.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
    // Set photo
    contentValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO, contactDto.getPhoto());
    // Set photo file id.
    contentValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO_FILE_ID, contactDto.getPhotoFieldId());

    // Insert to data table.
    contentResolver.insert(ContactsContract.Data.CONTENT_URI, contentValues);
}

3.18 ContactDTO Java File.

ContactDTO.java

package com.dev2qa.example.datasharing.contacts.dto;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jerry on 1/26/2018.
 */

public class ContactDTO {

    // Contact belong group fields.
    private long groupId;

    // Contacts id.
    private long contactId;

    // Raw contacts id. Has same value of contact id.
    private long rawContactId;

    // Contact structured name fields.
    private String displayName;
    private String givenName;
    private String familyName;

    // Contact nickname fields.
    private String nickName;

    // Contact organization fields.
    private String company;
    private String department;
    private String title;
    private String jobDescription;
    private String officeLocation;

    // Contact phone list.
    private List<DataDTO> phoneList = new ArrayList<DataDTO>();

    // Contact email list
    private List<DataDTO> emailList = new ArrayList<DataDTO>();

    // Contact address list.
    private List<DataDTO> addressList = new ArrayList<DataDTO>();

    // Contact website list.
    private List<DataDTO> websiteList = new ArrayList<DataDTO>();

    // Contact note.
    private String note;

    // Contact im list.
    private List<DataDTO> imList = new ArrayList<DataDTO>();

    // Contact postal fields.
    private String country;
    private String city;
    private String postCode;
    private String street;
    private String region;
    private long postType;

    // Contact identity fields.
    // Identity value
    private String identity;
    // Identity card, passport etc.
    private String namespace;

    // Contact photo fields.
    private String photo;
    private String photoFieldId;

    public long getContactId() {
        return contactId;
    }

    public void setContactId(long contactId) {
        this.contactId = contactId;
    }

    public long getRawContactId() {
        return rawContactId;
    }

    public void setRawContactId(long rawContactId) {
        this.rawContactId = rawContactId;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public String getGivenName() {
        return givenName;
    }

    public void setGivenName(String givenName) {
        this.givenName = givenName;
    }

    public String getFamilyName() {
        return familyName;
    }

    public void setFamilyName(String familyName) {
        this.familyName = familyName;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<DataDTO> getPhoneList() {
        return phoneList;
    }

    public void setPhoneList(List<DataDTO> phoneList) {
        this.phoneList = phoneList;
    }

    public List<DataDTO> getEmailList() {
        return emailList;
    }

    public void setEmailList(List<DataDTO> emailList) {
        this.emailList = emailList;
    }

    public List<DataDTO> getAddressList() {
        return addressList;
    }

    public void setAddressList(List<DataDTO> addressList) {
        this.addressList = addressList;
    }

    public List<DataDTO> getWebsiteList() {
        return websiteList;
    }

    public void setWebsiteList(List<DataDTO> websiteList) {
        this.websiteList = websiteList;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getJobDescription() {
        return jobDescription;
    }

    public void setJobDescription(String jobDescription) {
        this.jobDescription = jobDescription;
    }

    public String getOfficeLocation() {
        return officeLocation;
    }

    public void setOfficeLocation(String officeLocation) {
        this.officeLocation = officeLocation;
    }

    public List<DataDTO> getImList() {
        return imList;
    }

    public void setImList(List<DataDTO> imList) {
        this.imList = imList;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }


    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }

    public String getIdentity() {
        return identity;
    }

    public void setIdentity(String identity) {
        this.identity = identity;
    }

    public String getNamespace() {
        return namespace;
    }

    public void setNamespace(String namespace) {
        this.namespace = namespace;
    }

    public String getPhoto() {
        return photo;
    }

    public void setPhoto(String photo) {
        this.photo = photo;
    }

    public String getPhotoFieldId() {
        return photoFieldId;
    }

    public void setPhotoFieldId(String photoFieldId) {
        this.photoFieldId = photoFieldId;
    }

    public long getGroupId() {
        return groupId;
    }

    public void setGroupId(long groupId) {
        this.groupId = groupId;
    }

    public String getPostCode() {
        return postCode;
    }

    public void setPostCode(String postCode) {
        this.postCode = postCode;
    }

    public long getPostType() {
        return postType;
    }

    public void setPostType(long postType) {
        this.postType = postType;
    }
}

3.19 DataDTO Java File.

DataDTO.java

package com.dev2qa.example.datasharing.contacts.dto;

/**
 * Created by Jerry on 1/26/2018.
 */

public class DataDTO {

    private int dataType;

    private String dataValue;

    public int getDataType() {
        return dataType;
    }

    public void setDataType(int dataType) {
        this.dataType = dataType;
    }

    public String getDataValue() {
        return dataValue;
    }

    public void setDataValue(String dataValue) {
        this.dataValue = dataValue;
    }
}

Reference

  1. How To Get Contact In Android Programmatically
  2. Android Contacts Database Structure
  3. Android Contacts Fields, Data Table Columns And Data Mimetype Explain
  4. Android Marshmallow Runtime Permission Example

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.