javaandroidandroid-studioandroid-contactscontactscontract

How to add new field to a contact in android


I want to add new email address to an exist contact.

I use this code:

    ArrayList<ContentProviderOperation> insertEmailList =
            new ArrayList<ContentProviderOperation>();
    Uri uri=null;
    for (ContactEmail contactEmail : emails) {
        values.put(ContactsContract.Data.RAW_CONTACT_ID, id);
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
        values.put(ContactsContract.CommonDataKinds.Email.ADDRESS, contactEmail.getEmailAddress());
        values.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_CUSTOM);
        uri=contentResolver.insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
    }

When run this code uri is content://com.android.contacts/data/2135 but my contact is not updated.my app run without exception.


Solution

  • enter image description here

    Image from Get Contact Emails By Content Provider - Android Example

            Cursor mRawContactCursor = context.getContentResolver().query(
                ContactsContract.RawContacts.CONTENT_URI,
                null,
                ContactsContract.Data.CONTACT_ID + " = ?",
                new String[] {ID},
                null);
        mRawContactCursor.moveToFirst();
        String rawId = mRawContactCursor.getString(mRawContactCursor.getColumnIndex(ContactsContract.RawContacts._ID));
    

    use this code to find _ID or RAW_CONTACT_ID then update or insert to contact.

            for (ContactEmail contactEmail : emails) {
            values.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.Email.ADDRESS, "a@a.com");
            values.put(ContactsContract.CommonDataKinds.Email.TYPE, type.home);
            contentResolver.insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
        }