Display contacts from address book in Android

In my last post, I had explained how to add new contacts using the Contacts Provider component in Android. Moving on, we will now learn how to display existing phone book contacts using the concept of Cursors. The Cursor interface provides random read-write access to the result set returned by a database query.

As mentioned on the developer’s page, cursor implementations are not required to be synchronized so code using a Cursor from multiple threads should perform its own synchronization when using the Cursor.

Through this post, we will learn how to display existing phone book and Skype contacts using Cursors.

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

Open the Eclipse IDE and create a new Activity class called DisplayContactListActivity in any of your existing Android projects and add the following code!

DisplayContactListActivity.java

package com.example;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class DisplayContactListActivity extends Activity {

	private Button m_objBtnSkypeContact;
	private Button m_objBtnPhoneContact;
	private TextView m_objDisplayContact;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_display_contact);

		m_objBtnSkypeContact = (Button)findViewById(R.id.btnSkypeContact);
		m_objBtnPhoneContact = (Button)findViewById(R.id.btnPhoneContact);
		m_objDisplayContact = (TextView)findViewById(R.id.txtDisplayContact);

		//skype phone contact button event
		m_objBtnSkypeContact.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try{
					m_objDisplayContact.setText("");
					getSkypeContactsList();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});


		//phone contact button event
		m_objBtnPhoneContact.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try{
					m_objDisplayContact.setText("");
					getPhoneContactsList();
				}catch(Exception ex){
					ex.printStackTrace();
				}
			}
		});
	}

	/**
	 * 
	 * This function is used to display the list of Skype contacts
	 */
	private void getSkypeContactsList() {
		StringBuffer strSkypeContactBuffer = new StringBuffer();
		Cursor objCursor = getContentResolver().query(
				Data.CONTENT_URI,
				new String[] { Data.CONTACT_ID, Data.DATA1 },
				Data.MIMETYPE + "= ?", 
				new String[] { "vnd.android.cursor.item/com.skype.android.skypecall.action" },
				null);

		while (objCursor != null && objCursor.moveToNext()) {
			long contact = objCursor.getLong(0);
			String skype = objCursor.getString(1);

			Log.i("ContactsApp" , " " + "contact " + contact + " has skype username: " + skype);
			strSkypeContactBuffer.append("Contact " + contact + " has skype username: " + skype + "\n");

		}

		//display contact details
		m_objDisplayContact.setText(strSkypeContactBuffer.toString());
	}

	/**
	 * 
	 * 
	 * This function is used to display the existing phone contacts
	 */
	private void getPhoneContactsList() {
		StringBuffer strPhoneContactBuffer = new StringBuffer();
		ContentResolver objContentResolver = getContentResolver();
		Cursor objCursor = objContentResolver.query(ContactsContract.Contacts.CONTENT_URI,
				null, null, null, null);
		if (objCursor.getCount() > 0) {
			while (objCursor.moveToNext()) {
				String id = objCursor.getString(objCursor.getColumnIndex(ContactsContract.Contacts._ID));
				String name = objCursor.getString(objCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				if (Integer.parseInt(objCursor.getString(
						objCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
					Cursor objContactCursor = objContentResolver.query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
							new String[]{id}, null);
					while (objContactCursor.moveToNext()) {
						String phoneNo = objContactCursor.getString(objContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						Log.i("ContactsApp", "Name: " + name + ", Phone No: " + phoneNo);
						strPhoneContactBuffer.append("Name: " + name + ", Phone No: " + phoneNo + "\n");
						
					}
					objContactCursor.close();
				}
			}
		}

		//display contact details
		m_objDisplayContact.setText(strPhoneContactBuffer.toString());
	}
}

activity_display_contact.xml

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

    <Button
        android:id="@+id/btnPhoneContact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="@string/lbl_phone_contact" />

    <Button
        android:id="@+id/btnSkypeContact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnPhoneContact"
        android:layout_centerInParent="true"
        android:text="@string/lbl_skype_contact" />

    <TextView
        android:id="@+id/txtDisplayContact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnSkypeContact"
        android:layout_centerInParent="true" />

</RelativeLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- Display contact demo -->
    <string name="lbl_phone_contact">Show Phone contacts</string>
    <string name="lbl_skype_contact">Show Skype contacts</string>
</resources>

No changed are to be made to the AndroidManifest.xml file. Run the application on an Android device and you should be able to see the following output!

Screenshot_2015-11-09-09-04-47

Now, click on any of the buttons to retrieve the contact list.

That’s it then for this Android tip. Stay tuned for more! 🙂

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! 🙂