Read and display phone contacts in android

In this tutorial we will learn how to read and display phone contacts in android. Here i am fetching the contact and just displaying name and number as toast. You can use the name and number to display in a listview or any other widget based on your requirement.

Add the following function into your activity class file

public void GetAllContacts(){

ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);

if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));

if (cursor.getInt(cursor.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor number_cursor = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);

while (number_cursor.moveToNext()) {
String phone = number_cursor.getString(number_cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(MainActivity.this, "Contact name: " + name
+ ", Phone No: " + phone, Toast.LENGTH_SHORT).show();
}

number_cursor.close();
}
}
}
}

Call the above function when you want to read the contact list.

Note : If you want to display the contact in a listview you need to have an arraylist and instead of displaying toast add the name and number to arraylist and set it to listview adapter. Refer the following tutorial if you are not familiar with implementing a listview

Android listview example

Android custom listview with images

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

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