Using Content Resolver to List Contacts – Android

By | October 30, 2018

Here is a simple example to list contacts in android using the Content Resolver.

Note :

You need to have two things before accessing contacts.

1. Contacts Permission in the Android Manifest

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

2. Ask Runtime permission from the user

Contacts Android

Contacts Android – Content Resolver

Code

Here is our MainActivity that lists the contacts.

MainActivity.java

package contacts.coderzheaven.com.samplesproject;

import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.Toast;

import static contacts.coderzheaven.com.samplesproject.ContactListAdapter.CONTACT_PROJECTION;

public class MainActivity extends AppCompatActivity {

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

    private void setContacts() {
        ContentResolver content = getContentResolver();
        Cursor cursor = content.query(ContactsContract.Contacts.CONTENT_URI,
                CONTACT_PROJECTION, null, null, null);
        ContactListAdapter adapter = new ContactListAdapter(
                this, cursor);
        ListView listView = findViewById(R.id.listView);
        listView.setAdapter(adapter);
    }

    private void checkContactPermissions() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] PERMISSIONS = {android.Manifest.permission.READ_CONTACTS};
            if (!hasPermissions(this, PERMISSIONS)) {
                ActivityCompat.requestPermissions(this, PERMISSIONS, 100);
            } else {
                setContacts();
            }
        } else {
            setContacts();
        }
    }

    private static boolean hasPermissions(Context context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    setContacts();
                } else {
                    Toast.makeText(this, "The app was not allowed to read your contact", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

Adapter Class

Below is the adapter class for the Listview in the UI.
We name it “ContactListAdapter.java”.

package contacts.coderzheaven.com.samplesproject;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FilterQueryProvider;
import android.widget.Filterable;
import android.widget.TextView;

class ContactListAdapter extends CursorAdapter implements
        Filterable {

    public ContactListAdapter(Context context, Cursor c) {
        super(context, c);
        mContent = context.getContentResolver();
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        final LayoutInflater inflater = LayoutInflater.from(context);
        final TextView view = (TextView) inflater.inflate(
                android.R.layout.simple_dropdown_item_1line, parent, false);
        view.setText(cursor.getString(COLUMN_DISPLAY_NAME));
        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ((TextView) view).setText(cursor.getString(COLUMN_DISPLAY_NAME));
    }

    @Override
    public String convertToString(Cursor cursor) {
        return cursor.getString(COLUMN_DISPLAY_NAME);
    }

    @Override
    public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
        FilterQueryProvider filter = getFilterQueryProvider();
        if (filter != null) {
            return filter.runQuery(constraint);
        }

        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI,
                Uri.encode(constraint.toString()));
        return mContent.query(uri, CONTACT_PROJECTION, null, null, null);
    }

    private ContentResolver mContent;

    public static final String[] CONTACT_PROJECTION = new String[]{
            ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME};

    private static final int COLUMN_DISPLAY_NAME = 1;
}

Layout

Finally the layout. The layout is simple, it just contains a Listview.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="20dp">

    <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content" />

</LinearLayout>

Download Source Code

You can download the full android studio source code from here.

Leave a Reply

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