Adding contacts in Android

Hi everyone!

The Android SDK allows developers to add new contacts using the Contacts Provider component. As mentioned on the developer’s page, the Contacts Provider is the source of data you see in the device’s contacts application, and you can also access its data in your own application and transfer data between the device and online services. The provider accommodates a wide range of data sources and tries to manage as much data as possible for each person, with the result that its organization is complex.

Developers can access the Contacts Provider information directly by calling ContentResolver methods or by sending intents to a pre-installed contacts application. Through this post, we will learn how to add new contacts to our existing phone address book.

Pre-requisites: Eclipse IDE, Android SDK (Target API level: 19)

In any of your existing Android projects, create a new Activity class called AddContactActivity and add the following code!

AddContactActivity.java

package com.example;

import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddContactActivity extends Activity {

	private Button m_objBtnAddContact;
	private EditText m_objInputContactName, m_objInputContactEmail, m_objInputContactMobNo;
	public static final String LOG_TAG = "AddContactDemo";
	public static final String ACCOUNT_TYPE = "REPLACE_YOUR_GMAIL_ACCOUNT_ADDRESS";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_contact);

		m_objBtnAddContact = (Button)findViewById(R.id.btnAddContact);
		m_objInputContactName = (EditText)findViewById(R.id.inputContactName);
		m_objInputContactEmail = (EditText)findViewById(R.id.inputContactEmail);
		m_objInputContactMobNo = (EditText)findViewById(R.id.inputContactMobNo);

		//add new contact button event
		m_objBtnAddContact.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				try{
					
					String strContactName = m_objInputContactName.getEditableText().toString();
					String strContactEmail = m_objInputContactEmail.getEditableText().toString();
					String strContactMobNumber = m_objInputContactMobNo.getEditableText().toString();

					if(!isNullOrBlank(strContactName) && !isNullOrBlank(strContactEmail) && !isNullOrBlank(strContactMobNumber)){
						if(!contactExists(AddContactActivity.this, strContactMobNumber)){
							Contact objContact = new Contact(strContactName, strContactMobNumber, strContactEmail);
							addContactsToAddressBook(objContact);
						}else{
							Toast.makeText(getApplicationContext(), "Contacts already exists", Toast.LENGTH_LONG).show();
						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
	}


	/**
	 * This method is used to determine if a particular contact already exists
	 * @param Activity instance
	 * @param mobile number
	 * @return
	 */
	public boolean contactExists(Activity p_objActivity, String p_strMobileNumber) {
		if (p_strMobileNumber != null) {
			Uri objLookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(p_strMobileNumber));
			String[] objPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
			Cursor objCursor = p_objActivity.getContentResolver().query(objLookupUri, objPhoneNumberProjection, null, null, null);
			try {
				if (objCursor.moveToFirst()) {
					return true;
				}
			} finally {
				if (objCursor != null)
					objCursor.close();
			}
			return false;
		} else {
			return false;
		}
	}

	/**
	 * This function is used to check if a string is null or empty
	 * @param p_strInput
	 * @return true if string is null or empty
	 */
	public static boolean isNullOrBlank(String p_strInput){
		return (null== p_strInput || p_strInput.trim().equals(""));
	}

	/**
	 * This function is used to add a new contact to address book
	 * 
	 * @param contact
	 */
	public void addContactsToAddressBook(Contact contact){
		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
		ops.add(ContentProviderOperation.newInsert(
				ContactsContract.RawContacts.CONTENT_URI)
				.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, ACCOUNT_TYPE)
				.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "com.google")
				.build()
				);

		if(contact != null){
			//add contact name
			ops.add(ContentProviderOperation.newInsert(
					ContactsContract.Data.CONTENT_URI)              
					.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
					.withValue(ContactsContract.Data.MIMETYPE,
							ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
							.withValue(
									ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,     
									contact.getName()).build()
					);

			//add  contact email
			ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
					.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
					.withValue(ContactsContract.Data.MIMETYPE,
							ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
							.withValue(ContactsContract.CommonDataKinds.Email.DATA, contact.getEmailId())
							.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
							.build());

			//add contact mobile no
			ops.add(ContentProviderOperation.
					newInsert(ContactsContract.Data.CONTENT_URI)
					.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
					.withValue(ContactsContract.Data.MIMETYPE,
							ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
							.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contact.getMobileNo())
							.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
									ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
									.build()
					);

			// Asking the Contact provider to create a new contact                  
			try {
				getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
			} 
			catch (Exception e) {               
				e.printStackTrace();
				Toast.makeText(getApplicationContext(), "Unable to add contact!", Toast.LENGTH_LONG).show();
			}
		}

		Toast.makeText(getApplicationContext(), "Contact added!", Toast.LENGTH_LONG).show();
	}


}

activity_add_contact.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txtContactName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/lbl_contact_name" >
    </TextView>

    <EditText
        android:id="@+id/inputContactName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/lbl_contact_name"
        android:inputType="text" >
    </EditText>

    <TextView
        android:id="@+id/txtContactEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/lbl_contact_emailid" >
    </TextView>

    <EditText
        android:id="@+id/inputContactEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/lbl_contact_emailid"
        android:inputType="textEmailAddress" >
    </EditText>

    <TextView
        android:id="@+id/txtContactMobNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/lbl_contact_mobnumber" >
    </TextView>

    <EditText
        android:id="@+id/inputContactMobNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/lbl_contact_mobnumber"
        android:inputType="number" >
    </EditText>

    <Button
        android:id="@+id/btnAddContact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:hint="@string/lbl_add_contact" >
    </Button>

</LinearLayout>

strings.xml

 <string name="lbl_contact_name">Enter contact name</string>
    <string name="lbl_contact_emailid">Enter contact email ID</string>
    <string name="lbl_contact_mobnumber">Enter contact mobile number</string>
    <string name="lbl_add_contact">Add contact
</string>

Before running the application on a physical device, one needs to add the below permissions in the AndroidManifest.xml file

AndroidManifest.xml

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

Finally, if no errors occur you should be able to see the below output on running the application.

Main screen

Main screen

Adding new contact

Adding new contact

Contact already exists

Contact already exists

In the next post, we will see how to fetch and display the list of contacts! 🙂