Android Read Contact Name and Phone Number using CursorLoader

By Arvind Rai, July 03, 2015
On this page we will learn how to read contact name and phone number using CursorLoader in android with example. CursorLoader extends AsyncTaskLoader and works as background thread which does not block UI. Reading content from mobile is good example to use CursorLoader. In this example we will read contact display name and phone number. For this create instance of CursorLoader passing Phone.CONTENT_URI and finally iterate android Cursor to fetch data. To perform reading operation we have to provide READ_CONTACTS permission in AndroidManifest.xml as below.
<uses-permission android:name="android.permission.READ_CONTACTS" />
 

CursorLoader

android.content.CursorLoader is a Loader that fetches data from ContentResolver. CursorLoader extends AsyncTaskLoader and in this way it perform its work using background thread without blocking UI. To initiate it we use the constructor as below.
CursorLoader(Context context, Uri uri, String[] projection, String selection, 
                                    String[] selectionArgs, String sortOrder)
  
The meaning of parameters are as follows:
context : Context of application environment.
uri : URI with content:// pattern that retrieves content.
projection : List of columns to return and if null it will return all columns.
selection : A filter to return rows. Format is as SQL query.
sortOrder : Type of order as SQL ORDER BY and if null, output will be unordered.

LoaderManager.LoaderCallbacks

This is a callback interface for client. While using it we have to override the following methods.
onCreateLoader(int id, Bundle args): Creates new loader for the given id.
onLoadFinished(Loader loader, D data): It is called when previously created loader has finished its load.
onLoaderReset(Loader loader): It is called when previously created loader is being reset.

Read Contact URI using Phone.CONTENT_URI

Find the code snippet to implement onCreateLoader where we will create instance of CursorLoader.
public Loader onCreateLoader(int arg0, Bundle arg1) {
  Uri CONTENT_URI = Phone.CONTENT_URI;
  return new CursorLoader(this, CONTENT_URI, null,null, null, null);
}  

Use android.database.Cursor to Iterate rows

Inside onLoadFinished we will iterate rows fetching from Cursor.
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
  StringBuilder sb = new StringBuilder();
  cursor.moveToFirst();
  while (!cursor.isAfterLast()) {
       sb.append("\n" + cursor.getString(cursor.getColumnIndex(DISPLAY_NAME)));
       sb.append(":" + cursor.getString(cursor.getColumnIndex(NUMBER)));
       cursor.moveToNext();
  }
  textView.setText(sb);
} 

Complete Example

Now find the complete code where we are showing the demo to retrieve contact display name and phone number.
MainActivity.java
package com.concretepage;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {
         TextView textView = null;
         String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
         String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
	 protected void onCreate(Bundle savedInstanceState) {
		  super.onCreate(savedInstanceState);
		  setContentView(R.layout.main);
		  textView = (TextView) findViewById(R.id.out);
		  getSupportLoaderManager().initLoader(1, null, this);
	}
        public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		  Uri CONTENT_URI = Phone.CONTENT_URI;
		  return new CursorLoader(this, CONTENT_URI, null,null, null, null);
	}
	public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
		  StringBuilder sb = new StringBuilder();
		  cursor.moveToFirst();
		  while (!cursor.isAfterLast()) {
			   sb.append("\n" + cursor.getString(cursor.getColumnIndex(DISPLAY_NAME)));
			   sb.append(":" + cursor.getString(cursor.getColumnIndex(NUMBER)));
			   cursor.moveToNext();
		  }
		  textView.setText(sb);
	 }
	 public void onLoaderReset(Loader<Cursor> loader) {
	 }
	 @Override
	 protected void onDestroy() {
    	         super.onDestroy();
	 }
	 @Override
	 public boolean onCreateOptionsMenu(Menu menu) {
		  return true;
	 }
} 

main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
    android:background="#D1C4E9"
    tools:context=".MainActivity" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
	android:layout_gravity="center"
	android:textColor="#FF8A80"
	android:textSize="25sp"
	android:id="@+id/out"/>
</RelativeLayout> 

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.concretepage"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="11"/>
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <application
        android:allowBackup ="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity  android:name=".MainActivity" android:theme="@android:style/Theme.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

Output

Android Read Contact Name and Phone Number using CursorLoader Example

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us