Fetch Contacts And Display In A Listview In Android


Here I am going to describe how we can fetch all the contacts from our Android device and display them in a simple ListView. There will be some situations where we need to get all the contacts on our phone. Here I am explaining this in detail. We need to send a query to the contentResolver and this will return a cursor to us. We need to pass a URI to the cursor to get the cursor. The cursor will point to a particular row. We can query like the following to get the contacts from Android.
  1. cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);     
This will return the cursor that contains all the contacts on the phone. We need to iterate and get the values by specifying the column name.
For creating the sample application, first create your layout file which will contain a ListView only like the following,
  1. xmlns:android="http://schemas.android.com/apk/res/android"  
  2. xmlns:tools="http://schemas.android.com/tools"   
  4. <RelativeLayout>        
  5.  android:layout_width="match_parent"        
  6.  android:layout_height="match_parent"            
  7.  android:paddingBottom="@dimen/activity_vertical_margin"             
  8.  android:paddingLeft="@dimen/activity_horizontal_margin"             
  9.  android:paddingRight="@dimen/activity_horizontal_margin"             
  10.  android:paddingTop="@dimen/activity_vertical_margin"            
  11.  tools:context=".MainActivity">  
  13.     <ListView            
  14.  android:id="@+id/listView"             
  15.  android:layout_width="fill_parent"           
  16.  android:layout_height="wrap_content" />  
  17. </RelativeLayout>  
Now in the java file bind this listview like the following,
  1. listView = (ListView) findViewById(R.id.listView);   
Now get the cursor by querying to the content resolver,
  1. cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);  
Here we will get the cursor, now we need to get only whatever the files we needed like contact display name, number, email id, etc.
  1. String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};    
Now we need to specify the id of the elements in rows,
  1. int[] to = {android.R.id.text1, android.R.id.text2};   
Now we need to create the list adapter like the following,
  1. SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from, to);    
Here we are using Android's built in adapter to the listview.
The last step is we need to set this adapter to the listview with setAdapter(),
  1. listView.setAdapter(adapter);    
Now run the app and all your contacts will be shown in the listview of your application.
Please see the screenshots,