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.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentValues;
import android.net.Uri;
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. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        addContact("Coderz","1234567890");
        addContact("James","5656215521");
        addContact("John","4545454545");
        addContact("Mary","9632587410");
        addContact("Peter","4561237890");
    }
   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.clear();
        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??

    Reply
  3. Gobinda

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

    Reply
  4. Abilash

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

    Reply
  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?

    Reply
  6. Deepak Kishore

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

    Reply

Leave a Reply to Abilash Cancel reply

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