Android Programming: Reading Phone Contacts


In this Article, we will write code to read User’s name and phone contact number.

Below are the main activities that we need to incorporate in the code:

  1. Assigning Read access permission to read user’s contacts. Add the below line to AndroidManifest.xml file:

 

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

 

Or add the permissions from the AndroidMenifest.xml UI as shown below:

 

clip_image002

 

2.  Below is the code for activity_main.xml where we have defined TextView where we will display the User’s name and contact number.

 

 

<LinearLayout 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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/tvDemo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

</LinearLayout>

 

 

3) Below is the Java code from MainActivity.java file: In this file, the function that is fetching the User’s contact details is GetMyPhoneContacts(). In this function, we have used a column list and a query which will return User’s contact details in the cursor.

Below is the information about the query method that we have used:

Cursor android.content.ContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)

Query the given URI, returning a Cursor over the result set.

Parameters

uri

The URI, using the content:// scheme, for the content to retrieve.

projection

A list of which columns to return. Passing null will return all columns, which is inefficient.

selection

A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI.

selectionArgs

You may include ?s in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection. The values will be bound as Strings.

sortOrder

How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered. We have used Ascending order in this example.

Once the above query will return data in cursor, we will fetch the individual row in do while loop on the cursor. In the loop we are fetching the name and contact number of the user and appending it to the TextView.

 

 

 

package com.example.testapp;

import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.app.Activity;
import android.content.res.Configuration;
import android.database.Cursor;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

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

        GetMyPhoneContacts();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_main);
		super.onConfigurationChanged(newConfig);
	}

	public void GetMyPhoneContacts()
	{
		String[] mProjection=new String[]
				{
					ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
					ContactsContract.CommonDataKinds.Phone.NUMBER
				};

		String strName = null;
		String strPhoneNumber = null;
		TextView txtvw = (TextView) findViewById(R.id.tvDemo);

		Cursor curPhoneContacts = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, mProjection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " Asc");

		curPhoneContacts.moveToFirst();

		do
		{

			strName = curPhoneContacts.getString(curPhoneContacts.getColumnIndex(Contacts.DISPLAY_NAME));
			strPhoneNumber = curPhoneContacts.getString(curPhoneContacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

			txtvw.append("\nName-->" + strName + "\n");
			txtvw.append("Phone Number-->" + strPhoneNumber + "\n\n\n");

		}while (curPhoneContacts.moveToNext());
		curPhoneContacts.close();
	}

}

 

 

 

Result:

 

 

 

clip_image002[6]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s