Retrieving a List of Contacts in Android Example

In order to access contacts in Android we need to declare a permission in AndroidManifest.xml file

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


To use RecyclerView in Android you need to add following dependencies in build.gradle file

compile 'com.android.support:recyclerview-v7:23.0.1'


In this example we need to create

    Activity

         AllContacts.java: contains java file and xml layout file
             AllContacts.java: retrieve all contacts and add it to ArrayList and pass to Adapter
             activity_all_contacts.xml: add a recyclerView to display a list of contacts

    Adapter

        AllUsersAdapter.java
            Create a constructor to receive List of Users passed by the Activity Class

            Create a class ContactViewHolder.java that will extends RecyclerView.ViewHolder
       
            Implement RecyclerView.Adapter and override three methods:
                onCreateViewHolder(…)
                onBindViewHolder (…)
                getItemCount(…)


    Layout



        single_contact_view.xml: for single contact layout inside RecyclerView
Accessing a List of Contacts in Android
Retrieving a List of Contacts in Android

Source Code:

activity_all_contacts.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"
    tools:context=".AllContacts">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvContacts"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>

</RelativeLayout>
 
single_contact_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="#dddddd">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/ivContactImage"
            android:layout_width="55dp"
            android:layout_height="55dp"
            android:layout_marginLeft="10dp"
            android:layout_marginStart="10dp"
            android:src="@drawable/ic_action_person"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center_vertical">

            <TextView
                android:id="@+id/tvContactName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginStart="10dp"
                android:textSize="16sp"
                android:textColor="@android:color/primary_text_light"
                android:text="Name"/>

            <TextView
                android:id="@+id/tvPhoneNumber"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginStart="10dp"
                android:textSize="14sp"
                android:textColor="@android:color/primary_text_light"
                android:text="Phone"/>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>
 
AllContactsAdapter.java
package com.sonevalley.sushil.retrievingcontacts;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class AllContactsAdapter extends RecyclerView.Adapter<AllContactsAdapter.ContactViewHolder>{

    private List<ContactVO> contactVOList;
    private Context mContext;
    public AllContactsAdapter(List<ContactVO> contactVOList, Context mContext){
        this.contactVOList = contactVOList;
        this.mContext = mContext;
    }

    @Override
    public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.single_contact_view, null);
        ContactViewHolder contactViewHolder = new ContactViewHolder(view);
        return contactViewHolder;
    }

    @Override
    public void onBindViewHolder(ContactViewHolder holder, int position) {
        ContactVO contactVO = contactVOList.get(position);
        holder.tvContactName.setText(contactVO.getContactName());
        holder.tvPhoneNumber.setText(contactVO.getContactNumber());
    }

    @Override
    public int getItemCount() {
        return contactVOList.size();
    }

    public static class ContactViewHolder extends RecyclerView.ViewHolder{

        ImageView ivContactImage;
        TextView tvContactName;
        TextView tvPhoneNumber;

        public ContactViewHolder(View itemView) {
            super(itemView);
            ivContactImage = (ImageView) itemView.findViewById(R.id.ivContactImage);
            tvContactName = (TextView) itemView.findViewById(R.id.tvContactName);
            tvPhoneNumber = (TextView) itemView.findViewById(R.id.tvPhoneNumber);
        }
    }
}
 
AllContacts.java
package com.sonevalley.sushil.retrievingcontacts;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class AllContacts extends AppCompatActivity {

    RecyclerView rvContacts;

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

        rvContacts = (RecyclerView) findViewById(R.id.rvContacts);

        getAllContacts();
    }

    private void getAllContacts() {
        List<ContactVO> contactVOList = new ArrayList();
        ContactVO contactVO;

        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {

                int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
                if (hasPhoneNumber > 0) {
                    String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                    contactVO = new ContactVO();
                    contactVO.setContactName(name);

                    Cursor phoneCursor = contentResolver.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{id},
                            null);
                    if (phoneCursor.moveToNext()) {
                        String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        contactVO.setContactNumber(phoneNumber);
                    }

                    phoneCursor.close();

                    Cursor emailCursor = contentResolver.query(
                            ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                            new String[]{id}, null);
                    while (emailCursor.moveToNext()) {
                        String emailId = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    }
                    contactVOList.add(contactVO);
                }
            }

            AllContactsAdapter contactAdapter = new AllContactsAdapter(contactVOList, getApplicationContext());
            rvContacts.setLayoutManager(new LinearLayoutManager(this));
            rvContacts.setAdapter(contactAdapter);
        }
    }
}

ContactVO.java
package com.sushil.tech.retrievingcontacts;

public class ContactVO {
    private String ContactImage;
    private String ContactName;
    private String ContactNumber;

    public String getContactImage() {
        return ContactImage;
    }

    public void setContactImage(String contactImage) {
        this.ContactImage = ContactImage;
    }

    public String getContactName() {
        return ContactName;
    }

    public void setContactName(String contactName) {
        ContactName = contactName;
    }

    public String getContactNumber() {
        return ContactNumber;
    }

    public void setContactNumber(String contactNumber) {
        ContactNumber = contactNumber;
    }
}


Screen Preview:

Accessing a List of Contacts in Android
Retrieving a List of Contacts in Android


SHARE
    Blogger Comment
    Facebook Comment

23 comments:

  1. yes their is NO ContactVO class

    ReplyDelete
  2. yes their is NO ContactVO class

    ReplyDelete
  3. ContactVO is a simple POJO Class for getters and setters. It has been added now.

    ReplyDelete
  4. Hi
    Nice share but it takes a lot of time to load contacts.

    ReplyDelete
  5. why u have not set contact image in onbind method

    ReplyDelete
  6. I can't read the data it show database can't be open.

    ReplyDelete
    Replies
    1. It may be because of you have not given contact access permission for your App

      Delete
  7. App getting crash.. When I open the apk in device

    ReplyDelete
    Replies
    1. failed to make and chown /acct/uid_10077: Read-only file system Like this

      Delete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Hello, This post help me a lot. Thanks a lot for it. But i have one doubt. If i want to display all the number of respective contact , for instance , contact ABC have 3 phonenumber. As per code, it will display only 1st one. Can you help me with that.

    ReplyDelete
  10. Hello, your tutorial is pretty nice. You only need to update it with contact's photo retrieval also. It will be great.

    ReplyDelete
  11. nice tutorial but naming conventions are not so good but keep it up

    ReplyDelete
  12. this make app crash or hang for long time

    ReplyDelete
  13. java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
    at android.view.LayoutInflater.from(LayoutInflater.java:228)
    at com.enrichtechnosoft.vishal.socialmediaapp.adapter.ContactsAdapter.onCreateViewHolder(ContactsAdapter.java:28)
    at com.enrichtechnosoft.vishal.socialmediaapp.adapter.ContactsAdapter.onCreateViewHolder(ContactsAdapter.java:16)

    error shown..pls help how to resolves..

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. I am getting always Zero(0) in hasPhoneNumber variable int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))); because of that I cant get Phone Number.. please help me.

    ReplyDelete
  16. Whats the purpose of Email datakind?

    ReplyDelete
  17. E/qhf: Stat call failed because file does not exist: /storage/emulated/0/Android/data/com.google.android.youtube/cache/exo/1/3629.1113075.1581170772264.v3.exo
    android.system.ErrnoException: stat failed: ENOENT (No such file or directory)
    it shows directory error how can i resolve this

    ReplyDelete
  18. How can I filter them if I want to use a search menu in a toolbar?

    ReplyDelete