Adding contacts programatically using Contacts Provider in Android – Example

September 24, 2012
By

In this article we will create an Android application which allows users to add new contacts to Android’s Contact Manager. We will make use Android’s Contacts content provider to add contacts to the Contact Manager.

An extension to this article is discussed in the article “Programatically adding contacts with photo using Contacts Provider in Android – Example“, where photos can also be added to the Android’s Contact Manager using Contacts Provider API.

This application is developed in Eclipse ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 ).


1. Create a new Android application project namely “ContactsAdd”

Create new Android application Project

Figure 1 : Create new Android application Project


2. Design application launcher icon

Design application launcher icon

Figure 2 : Design application launcher icon


3. Create a blank activity to define the class MainActivity

Create a blank activity

Figure 3 : Create a blank activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Delete Android’s Support library from this project, if exists

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.


6. Update the file res/values/strings.xml

<resources>
    <string name="app_name">ContactsAdd</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Add Contact Demo</string>
    <string name="hnt_et_name">Display Name</string>
    <string name="hnt_et_mobile_phone">Mobile Phone</string>
    <string name="hnt_et_home_phone">Home Phone</string>
    <string name="hnt_et_home_email">Home Email</string>
    <string name="hnt_et_work_email">Work Email</string>
    <string name="str_btn_add">Add Contact</string>
    <string name="str_btn_contacts">Contacts List</string>
</resources>

7. Update the file res/values/styles.xml

<resources>
    <style name="AppTheme" parent="android:Theme" />
</resources>

8. Update the file res/values-v11/styles.xml

<resources>
    <style name="AppTheme" parent="android:Theme.Holo" />
</resources>

9. Update the file res/values-v14/styles.xml

<resources>
    <style name="AppTheme" parent="android:Theme.Holo" />
</resources>

10. Update the layout file res/layout/activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <EditText
        android:id="@+id/et_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="@string/hnt_et_name" />

    <EditText
        android:id="@+id/et_mobile_phone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_name"
        android:inputType="phone"
        android:hint="@string/hnt_et_mobile_phone" />

    <EditText
        android:id="@+id/et_home_phone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_mobile_phone"
        android:inputType="phone"
        android:hint="@string/hnt_et_home_phone" />

    <EditText
        android:id="@+id/et_work_email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_home_phone"
        android:inputType="textEmailAddress"
        android:hint="@string/hnt_et_work_email" />

    <EditText
        android:id="@+id/et_home_email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_work_email"
        android:inputType="textEmailAddress"
        android:hint="@string/hnt_et_home_email" />

    <Button
        android:id="@+id/btn_add"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_home_email"
        android:text="@string/str_btn_add" />

    <Button
        android:id="@+id/btn_contacts"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_add"
        android:text="@string/str_btn_contacts" />
</RelativeLayout>


11. Update the class MainActivity in the file src/in/wptrafficanalyzer/contactsadd/MainActivity.java


package in.wptrafficanalyzer.contactsadd;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.RawContacts;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Creating a button click listener for the "Add Contact" button
        OnClickListener addClickListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                // Getting reference to Name EditText
                EditText etName = (EditText) findViewById(R.id.et_name);

                // Getting reference to Mobile EditText
                EditText etMobile = (EditText) findViewById(R.id.et_mobile_phone);

                // Getting reference to HomePhone EditText
                EditText etHomePhone = (EditText) findViewById(R.id.et_home_phone);

                // Getting reference to HomeEmail EditText
                EditText etHomeEmail = (EditText) findViewById(R.id.et_home_email);

                // Getting reference to WorkEmail EditText
                EditText etWorkEmail = (EditText) findViewById(R.id.et_work_email);

                ArrayList<ContentProviderOperation> ops =
                new ArrayList<ContentProviderOperation>();

                int rawContactID = ops.size();

                // Adding insert operation to operations list
                // to insert a new raw contact in the table ContactsContract.RawContacts
                ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                        .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                        .withValue(RawContacts.ACCOUNT_NAME, null)
                        .build());

                // Adding insert operation to operations list
                // to insert display name in the table ContactsContract.Data
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
                        .withValue(ContactsContract.Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
                        .withValue(StructuredName.DISPLAY_NAME, etName.getText().toString())
                        .build());

                // Adding insert operation to operations list
                // to insert Mobile Number in the table ContactsContract.Data
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
                        .withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
                        .withValue(Phone.NUMBER, etMobile.getText().toString())
                        .withValue(Phone.TYPE, CommonDataKinds.Phone.TYPE_MOBILE)
                        .build());

                // Adding insert operation to operations list
                // to  insert Home Phone Number in the table ContactsContract.Data
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
                        .withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
                        .withValue(Phone.NUMBER, etHomePhone.getText().toString())
                        .withValue(Phone.TYPE, Phone.TYPE_HOME)
                        .build());

                // Adding insert operation to operations list
                // to insert Home Email in the table ContactsContract.Data
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
                        .withValue(ContactsContract.Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
                        .withValue(Email.ADDRESS, etHomeEmail.getText().toString())
                        .withValue(Email.TYPE, Email.TYPE_HOME)
                        .build());

                // Adding insert operation to operations list
                // to insert Work Email in the table ContactsContract.Data
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
                        .withValue(ContactsContract.Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
                        .withValue(Email.ADDRESS, etWorkEmail.getText().toString())
                        .withValue(Email.TYPE, Email.TYPE_WORK)
                        .build());

                try{
                    // Executing all the insert operations as a single database transaction
                    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                    Toast.makeText(getBaseContext(), "Contact is successfully added", Toast.LENGTH_SHORT).show();
                }catch (RemoteException e) {
                    e.printStackTrace();
                }catch (OperationApplicationException e) {
                    e.printStackTrace();
                }
            }
        };

        // Creating a button click listener for the "Add Contact" button
        OnClickListener contactsClickListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                // Creating an intent to open Android's Contacts List
                Intent contacts = new Intent(Intent.ACTION_VIEW,ContactsContract.Contacts.CONTENT_URI);

                // Starting the activity
                startActivity(contacts);
            }
        };

        // Getting reference to "Add Contact" button
        Button btnAdd = (Button) findViewById(R.id.btn_add);

        // Getting reference to "Contacts List" button
        Button btnContacts = (Button) findViewById(R.id.btn_contacts);

        // Setting click listener for the "Add Contact" button
        btnAdd.setOnClickListener(addClickListener);

        // Setting click listener for the "List Contacts" button
        btnContacts.setOnClickListener(contactsClickListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


12. Update the file AndroidManifest.xml to provide the necessary permissions


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.contactsadd"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="5"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

13. Screenshots of the application

Entering new Contact Details

Figure 5 : Entering new Contact Details

Viewing the above added contact in Android's Contact Manager

Figure 6 : Viewing the above added contact in Android's Contact Manager


14. Download


15. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: ,

8 Responses to Adding contacts programatically using Contacts Provider in Android – Example

  1. bhupesh bhargava on October 23, 2012 at 3:57 pm

    Hi george,
    I am also using the similar process for inserting the contacts in android. But my application is slowing very slow process. means, for inserting 96 contacts it is taking almost 60 seconds. any guess for performance ??

  2. RAm on January 21, 2014 at 1:43 pm

    Thanks for you code…..Its is very helpful 4 me..Keep it up

  3. Chandru on February 9, 2014 at 1:59 pm

    Hi George,

    Thank you for your android tutorials. It is simply superb and easy to understand. No words to appreciate you. It would be even better if you add some samples for drag and drop tutorial, viewflipper, animations for layout, activity, fragment,etc.. Hope you will do it.
    I am a beginner if you have links for different tutorials or much needed basic codes
    Again Thanks from my heart

    Regards,
    Chandru

  4. Hemal Adani on October 17, 2014 at 5:22 pm

    Worked for me. Thank you so much

  5. Deepak Kishore on October 27, 2014 at 9:24 am

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

  6. Deepak Kishore on October 29, 2014 at 10:29 am

    I need to sync my app with contacts. For example if i sync facebook the contacts in facebook will be sync with my contacts how to do that for my app
    Thanks in advance

  7. sandeep on December 16, 2014 at 11:47 am

    Hi George,
    I want to show my app icon in phone book like whats app facebook and skype. How can I do that?

Leave a Reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner