How to get Contact Number and Name from Contactslist in Android

Hello Friends,

In this blog post, i am going brief how to get contact number from Android Mobile, and display it in ListView in Android.

Step 1:

First, you have to give user permission in manifest file. For that, add the following line in your application manifest file.

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

Step 2:

Include the following xml file in “Layout Folder”.

activity_main.xml


<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.splashscreen.MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" >
    </ListView>

</RelativeLayout>

Step 3:
Include the following java class in “Source Folder”.

MainActivity.java

public class MainActivity extends Activity {
String phoneNumber,name;
String[] stockArr;
JsonArray myCustomArray;

ArrayList <String> aa= new ArrayList<String>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		ListView listview = (ListView)findViewById(R.id.listView1);
		ArrayList<String> number = getCnumber();
		 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
	              android.R.layout.simple_list_item_1, android.R.id.text1, number);
		 listview.setAdapter(adapter); 
		
	}
	
public ArrayList<String> getCnumber()
	{
	ContentResolver cr=this.getContentResolver();
	Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
	     while (phones.moveToNext())
	     {
	      name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
	      phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
               
	       System.out.println(" Phone Nuber.................."+phoneNumber); 
	       aa.add(name);
	       aa.add(phoneNumber);
	       
	     }
		return aa;
		
	}
	
}

Screenshot
Screenshot_2014-12-21-11-28-26

Hope this blog post was helpful. Do let me know your feedback.

Comments
  1. iliya

Leave a Reply

Your email address will not be published. Required fields are marked *