Saturday, September 8, 2012

Read Contacts from Android Device

This is a sample activity which shows How to read the contacts of phone and display them in your application. Last topic published on this forum is Detect USB connection.
Underlying Algorithm:
Basic description of algorithm in step by step form:
1.) Create a Project ReadContacts.
2.) Put the following code snippet in res/layout/main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

   android:id ="@+id/con"
3.) Add the following permission in AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    <uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ReadContacts"
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
4.) Import the following packages in activity:
import android.database.Cursor;
import android.provider.ContactsContract;
import android.widget.TextView;
5.) Add some contacts in device/emulator.
6.) Run the Application.
Steps to Create:
1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. ReadContacts. Enter following information:
Project name: ReadContacts
Build Target: Android APIs2.1
Application name: ReadContacts
Package name: ReadContacts
Create Activity: ReadContacts
On Clicking Finish ReadContacts code structure is generated with the necessary Android Packages being imported along with ReadContacts class will look like following:
import android.os.Bundle;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.widget.TextView;
public class ReadContacts extends Activity {
        /** Called when the activity is first created. */
        public void onCreate(Bundle savedInstanceState) {
                TextView contactView = (TextView) findViewById(;
                Cursor cursor = getContacts();
                while (cursor.moveToNext()) {
                        String displayName =cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
                        contactView.append("Name: ");
        private Cursor getContacts() {
                // Run query
                Uri uri = ContactsContract.Contacts.CONTENT_URI;
                String[] projection = new String[] {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };
                String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ‘" + ("1") + "’";
                String[] selectionArgs = null;
                String sortOrder = ContactsContract.Contacts.DISPLAY_NAME+ " COLLATE LOCALIZED ASC";
                return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
Output –The final output:

No comments:

Post a Comment