Thursday , January 9 2025

How to get contact details in Android phone

contact

In this tutorial I am going to share code for getting phone contact detail from your android phone.
It will pick all the phone number, email and profile picture also.

1).  app/build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.w2class.main"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'com.android.support:cardview-v7:23.1.1'
    compile 'com.squareup.picasso:picasso:2.3.2'
    compile 'de.hdodenhof:circleimageview:2.1.0'
}

 

2).  MainActivity.java

package com.w2class.main;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends Activity {
    Activity _activity = MainActivity.this;

    RecyclerView recyclerView;
    ContactsAdapter mAdapter;
    ProgressDialog prg;
    ArrayList<Contact> contactList = new ArrayList<Contact>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview_category);

        // load contacts in asynctask thread
        new LoadContact().execute();

    }

    public void readContacts() {
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        String phone = null;
        String emailContact = null;
        String emailType = null;
        String image_uri = "";
        Bitmap bitmap = null;
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {

                Contact contact = new Contact();

                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                image_uri = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
                if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    System.out.println("name : " + name + ", ID : " + id);

                    contact.setContactName(name);

                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        System.out.println("phone" + phone);

                        contact.setPhoneNumber(phone);

                    }
                    pCur.close();
                    Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);
                    while (emailCur.moveToNext()) {
                        emailContact = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                        emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
                        System.out.println("Email " + emailContact + " Email Type : " + emailType);

                        contact.setEmail(emailContact);

                    }
                    emailCur.close();
                }
                if (image_uri != null) {
                    System.out.println(Uri.parse(image_uri));
                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(image_uri));

                        contact.setImage(bitmap);

                        System.out.println(bitmap);
                    } catch (FileNotFoundException e) { // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                // add contact in arraylist
                contactList.add(contact);

            }

        }
    }

    // set contact list in adapter
    private void setAdapter() {
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(_activity);
        recyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new ContactsAdapter(_activity, contactList);
        recyclerView.setAdapter(mAdapter);
    }

    protected class LoadContact extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            prg = ProgressDialog.show(_activity, null, "Please wait...", true);
        }

        @Override
        protected String doInBackground(String... params) {
            readContacts();
            return null;
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            prg.dismiss();
            setAdapter();

        }
    }


}

3. ContactsAdapter.java

you have to create a adapter for adding contact list in recyclerview.

package com.w2class.main;

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

import java.util.ArrayList;


public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.MyViewHolder> {

    Context mContext;
    ArrayList<Contact> contactList = new ArrayList<Contact>();

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView contactName, phone_number, email;
        public ImageView image;

        public MyViewHolder(View view) {
            super(view);
            contactName = (TextView) view.findViewById(R.id.name);
            phone_number = (TextView) view.findViewById(R.id.phone_number);
            image = (ImageView) view.findViewById(R.id.image);


        }

    }// end MyViewHolder class...........

    public ContactsAdapter(Context context, ArrayList<Contact> contactList) {
        this.mContext = context;
        this.contactList = contactList;
    }


    // add single item view
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.contact_sigle_item, parent, false);


        return new MyViewHolder(itemView);
    }

    // Used to set Tire
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {


        holder.contactName.setText(contactList.get(position).getContactName());
        holder.phone_number.setText(contactList.get(position).getPhoneNumber());

        if (contactList.get(position).getImage() == null) {
            holder.image.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_launcher));
        }else{
            holder.image.setImageBitmap(contactList.get(position).getImage());
        }
    }

    @Override
    public int getItemCount() {
        return contactList.size();
    }
}// end main class............................

4. Contact.java

package com.w2class.main;

import android.graphics.Bitmap;

import java.io.Serializable;

/**
 * Created by Peeyush on 7/29/2016.
 */
public class Contact implements Serializable {

    private String contactName;
    private String phoneNumber;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    private String email;
    private Bitmap image;

    public String getContactName() {
        return contactName;
    }

    public void setContactName(String contactName) {
        this.contactName = contactName;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public Bitmap getImage() {
        return image;
    }

    public void setImage(Bitmap image) {
        this.image = image;
    }
}

5. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">


    <android.support.v7.widget.RecyclerView

        android:id="@+id/recyclerview_category"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar"
        android:clipToPadding="false"
        android:fadingEdge="none"
        android:padding="5sp"></android.support.v7.widget.RecyclerView>

</ScrollView>

6. contact_single_item

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/product_item_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:clickable="true"
    android:focusable="true"
    app:cardBackgroundColor="@android:color/white"
    app:cardCornerRadius="4dp"
    app:cardElevation="3dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="2sp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="horizontal">


            <de.hdodenhof.circleimageview.CircleImageView
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:id="@+id/image"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:layout_marginLeft="6sp"
                android:src="@mipmap/ic_launcher"
                app:civ_border_width="2dp"
                app:civ_border_color="#ffffff"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="8sp"
                android:gravity="center"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:singleLine="true"
                    android:text="Peeyush singhal"
                    android:textColor="@android:color/black"
                    android:textSize="16sp" />

                <TextView
                    android:id="@+id/phone_number"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="4sp"
                    android:singleLine="false"
                    android:text="9530170876"
                    android:textColor="@android:color/darker_gray"
                    android:textSize="14sp" />

                <TextView
                    android:id="@+id/email"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="4sp"
                    android:singleLine="true"
                    android:text="peeyushsinghal94@gmail.com"
                    android:textColor="@android:color/darker_gray"
                    android:visibility="gone"
                    android:textSize="14sp" />

            </LinearLayout>
        </LinearLayout>
    </RelativeLayout>
</android.support.v7.widget.CardView>

 

About admin

Check Also

Binding JavaScript and Android Code – Example

When developing a web application that’s designed specifically for the WebView in your Android application, …

Leave a Reply