How to add a new contact programmatically in android?

By | June 18, 2012

We all know how to add a new contact to our android devices without programming right.
OK that’s a normal man’s use.
But what from a programmer’s view.

Add Contacts

This is the sample java code that helps you to add contact programatically.

package com.coderzheaven.pack;

import java.util.ArrayList;

import android.content.ContentProviderOperation;
import android.content.ContentValues;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Contacts.People;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.widget.Toast;

public class AddContactDemo extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
   private void addContact(String name, String phone) {
        ContentValues values = new ContentValues();
        values.put(People.NUMBER, phone);
        values.put(People.TYPE, Phone.TYPE_CUSTOM);
        values.put(People.LABEL, name);
        values.put(People.NAME, name);
        Uri dataUri = getContentResolver().insert(People.CONTENT_URI, values);
        Uri updateUri = Uri.withAppendedPath(dataUri, People.Phones.CONTENT_DIRECTORY);
        values.put(People.Phones.TYPE, People.TYPE_MOBILE);
        values.put(People.NUMBER, phone);
        updateUri = getContentResolver().insert(updateUri, values);

After running this programs please switch to contacts application on your device to see the result.

Please leave your comments and also share it if you like it.

7 thoughts on “How to add a new contact programmatically in android?

  1. Pingback: How to delete a contact in android?

  2. tahir

    Thanks for this useful post, Please tell me How to add contact to a specific group rather in contacts??

  3. Gobinda

    Thanks. But how to add photo with contact name and phone number. Please provide the answer

  4. Abilash

    thanks,plz tell me how to pass the datas from qrcode to contacts

  5. navid

    thank for your post
    but it work only in first run …
    and when i run it for another time i get this Error :
    java.lang.IllegalArgumentException: raw_contact_id is required

    can you guide me to right method?

  6. Deepak Kishore

    I want to sync my app with the contacts like whatsapp how to do it.Thanks in advance


Leave a Reply

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