How To Update Delete Android Contacts Programmatically

This article is one of the Android contact management series, it will tell you how to update or delete android contacts programmatically. If you need to read previous articles, you can read below two first.

  1. How To Add Contact In Android Programmatically
  2. How To Get Contact List In Android Programmatically

1. Update Android Contact Programmatically Steps.

  1. Call ContentResolver.query() method to get raw contact id in raw_contacts table by display name.
    /* Get raw contact id by contact given name and family name.
    *  Return raw contact id.
    * */
    private long getRawContactIdByName(String givenName, String familyName)
    {
        ContentResolver contentResolver = getContentResolver();
    
        // Query raw_contacts table by display name field ( given_name family_name ) to get raw contact id.
    
        // Create query column array.
        String queryColumnArr[] = {ContactsContract.RawContacts._ID};
    
        // Create where condition clause.
        String displayName = givenName + " " + familyName;
        String whereClause = ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY + " = '" + displayName + "'";
    
        // Query raw contact id through RawContacts uri.
        Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI;
    
        // Return the query cursor.
        Cursor cursor = contentResolver.query(rawContactUri, queryColumnArr, whereClause, null, null);
    
        long rawContactId = -1;
    
        if(cursor!=null)
        {
            // Get contact count that has same display name, generally it should be one.
            int queryResultCount = cursor.getCount();
            // This check is used to avoid cursor index out of bounds exception. android.database.CursorIndexOutOfBoundsException
            if(queryResultCount > 0)
            {
                // Move to the first row in the result cursor.
                cursor.moveToFirst();
                // Get raw_contact_id.
                rawContactId = cursor.getLong(cursor.getColumnIndex(ContactsContract.RawContacts._ID));
            }
        }
    
        return rawContactId;
    }
  2. Call ContentResolver.update() method to update related contact info ( phone number ) in data table by raw contact id, data mimetype ( vnd.android.cursor.item/phone_v2 ) and data type ( Phone.TYPE_MOBILE ). These three column value can uniquely identify one contact data record in data table.
    /*
     * Update contact phone number by contact name.
     * Return update contact number, commonly there should has one contact be updated.
     */
    private int  updateContactPhoneByName(String givenName, String familyName)
    {
        int ret = 0;
    
        ContentResolver contentResolver = getContentResolver();
    
        // Get raw contact id by display name.
        long rawContactId = getRawContactIdByName(givenName, familyName);
    
        // Update data table phone number use contact raw contact id.
        if(rawContactId > -1) {
            // Update mobile phone number.
            updatePhoneNumber(contentResolver, rawContactId, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE, "66666666666666");
    
            // Update work mobile phone number.
            updatePhoneNumber(contentResolver, rawContactId, ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE, "8888888888888888");
    
            // Update home phone number.
            updatePhoneNumber(contentResolver, rawContactId, ContactsContract.CommonDataKinds.Phone.TYPE_HOME, "99999999999999999");
    
            ret = 1;
        }else
        {
            ret = 0;
        }
    
        return ret;
    }
    
    /* Update phone number with raw contact id and phone type.*/
    private void updatePhoneNumber(ContentResolver contentResolver, long rawContactId, int phoneType, String newPhoneNumber)
    {
        // Create content values object.
        ContentValues contentValues = new ContentValues();
    
        // Put new phone number value.
        contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, newPhoneNumber);
    
        // Create query condition, query with the raw contact id.
        StringBuffer whereClauseBuf = new StringBuffer();
    
        // Specify the update contact id.
        whereClauseBuf.append(ContactsContract.Data.RAW_CONTACT_ID);
        whereClauseBuf.append("=");
        whereClauseBuf.append(rawContactId);
    
        // Specify the row data mimetype to phone mimetype( vnd.android.cursor.item/phone_v2 )
        whereClauseBuf.append(" and ");
        whereClauseBuf.append(ContactsContract.Data.MIMETYPE);
        whereClauseBuf.append(" = '");
        String mimetype = ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
        whereClauseBuf.append(mimetype);
        whereClauseBuf.append("'");
    
        // Specify phone type.
        whereClauseBuf.append(" and ");
        whereClauseBuf.append(ContactsContract.CommonDataKinds.Phone.TYPE);
        whereClauseBuf.append(" = ");
        whereClauseBuf.append(phoneType);
    
        // Update phone info through Data uri.Otherwise it may throw java.lang.UnsupportedOperationException.
        Uri dataUri = ContactsContract.Data.CONTENT_URI;
    
        // Get update data count.
        int updateCount = contentResolver.update(dataUri, contentValues, whereClauseBuf.toString(), null);
    }

2. Delete Android Contact Programmatically Steps.

  1. Invoke ContentResolver.query() method to get contact raw_contact id in raw_contacts table like above.
  2. Invoke ContectResolver.delete() method to delete contact info in data table, delete contact in contacts and raw_contacts table.
    /*
    * Delete contact by it's display name.
    * */
    private void deleteContact(String givenName, String familyName)
    {
        // First select raw contact id by given name and family name.
        long rawContactId = getRawContactIdByName(givenName, familyName);
    
        ContentResolver contentResolver = getContentResolver();
    
        //******************************* delete data table related data ****************************************
        // Data table content process uri.
        Uri dataContentUri = ContactsContract.Data.CONTENT_URI;
    
        // Create data table where clause.
        StringBuffer dataWhereClauseBuf = new StringBuffer();
        dataWhereClauseBuf.append(ContactsContract.Data.RAW_CONTACT_ID);
        dataWhereClauseBuf.append(" = ");
        dataWhereClauseBuf.append(rawContactId);
    
        // Delete all this contact related data in data table.
        contentResolver.delete(dataContentUri, dataWhereClauseBuf.toString(), null);
    
    
        //******************************** delete raw_contacts table related data ***************************************
        // raw_contacts table content process uri.
        Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI;
    
        // Create raw_contacts table where clause.
        StringBuffer rawContactWhereClause = new StringBuffer();
        rawContactWhereClause.append(ContactsContract.RawContacts._ID);
        rawContactWhereClause.append(" = ");
        rawContactWhereClause.append(rawContactId);
    
        // Delete raw_contacts table related data.
        contentResolver.delete(rawContactUri, rawContactWhereClause.toString(), null);
    
        //******************************** delete contacts table related data ***************************************
        // contacts table content process uri.
        Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
    
        // Create contacts table where clause.
        StringBuffer contactWhereClause = new StringBuffer();
        contactWhereClause.append(ContactsContract.Contacts._ID);
        contactWhereClause.append(" = ");
        contactWhereClause.append(rawContactId);
    
        // Delete raw_contacts table related data.
        contentResolver.delete(contactUri, contactWhereClause.toString(), null);
    
    }
(Visited 3,905 times, 1 visits today)
READ :   Android Contacts Fields, Data Table Columns And Data Mimetype Explain

3 Comments


  1. Been struggling hours with deleting properly a contact, (lot of useless code that did not work on the internet) until I found your solution.

    Thanks a lot.

    Reply

  2. I struggle with this problem. Could you give me some comments?

    There are several phone numbers with the same types.
    Ex: 0123xxxx (Type: Mobile), 0235xxxx (Type: Mobile), 083xxx (Type: Mobile).

    The user wants to change only one of them via checkbox.

    I use the same code but every time I run it it will change all of those same types. Is there any parameter more to discriminate those same types?

    Reply

    1. 1. You need select all the three record’s raw_contact_id, phone number, contact type.

      2. Then identify the three contact by their raw_contact_id, then update the number by the raw_contact_id, not by the type.

      3. Because raw_contact_id is unique, but type is same.

      Reply

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.