Android Contacts Example

Android Contacts

This is a simple snippet tutorial to show you how to fetch or pick contacts from the user’s device.

Android Contacts tutorial and Example.


import android.app.Activity;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.util.Log;

import org.json.JSONObject;

import java.util.concurrent.CountDownLatch;

public class ContactHelper {

    private static final String TAG = "ContactHelper";
    private Activity context;

    private JSONObject contacts;

    public ContactHelper(Activity context) {
        this.context = context;
    }

    public JSONObject queryContactList(){
        final CountDownLatch latch = new CountDownLatch(1);
        ContactsLoaderCallback callback = new ContactsLoaderCallback(context);
        callback.setQueryListener(new ContactsLoaderCallback.QueryListener() {
            @Override
            public void success(final JSONObject object) {
                contacts = object;
                latch.countDown();
            }
        });
        context.getLoaderManager().restartLoader(0,null,callback);

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return contacts;
    }

    public JSONObject pickContact(){
        return null;
    }

    public void queryContactNameList(){

        Cursor cursor = context.getContentResolver()
                .query(
                        ContactsContract.Contacts.CONTENT_URI,
                        new String[]{
                                ContactsContract.Contacts.DISPLAY_NAME
                        },
                        null,
                        null,
                        null
                );

        if (cursor != null && cursor.moveToFirst()){
            do {
                int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                String name = cursor.getString(nameIndex);
                Log.d(TAG, "queryContactNameList: n name = " + name);
            }while (cursor.moveToNext());

        }

    }

}

PermissionActivity

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class PermissionActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

Co

import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;

import com.jiangkang.tools.struct.JsonGenerator;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Created by jiangkang on 2017/9/13.
 */

public class ContactsLoaderCallback implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final String TAG = "ContactsLoaderCallback";

    private JSONObject result;

    private Context context;
    private QueryListener listener;

    public ContactsLoaderCallback(Context context) {
        this.context = context;
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        //指定获取_id和display_name两列数据,display_name即为姓名
        String[] projection = new String[]{
                ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME
        };
        CursorLoader loader = new CursorLoader(
                context,
                ContactsContract.Contacts.CONTENT_URI,
                projection,
                null,
                null,
                null
        );
        return loader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, final Cursor data) {

        if (data.isClosed()) {
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                handleCursor(data);
            }
        }).start();

    }

    private void handleCursor(Cursor data) {
        JSONArray jsonArray = new JSONArray();
        if (data != null && data.moveToFirst()) {
            do {
                String name = data.getString(
                        data.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)
                );
                int id = data.getInt(
                        data.getColumnIndex(ContactsContract.Contacts._ID)
                );

                //指定获取NUMBER这一列数据
                String[] phoneProjection = new String[]{
                        ContactsContract.CommonDataKinds.Phone.NUMBER
                };

                Cursor cursor = context.getContentResolver().query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        phoneProjection,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id,
                        null,
                        null
                );
                if (cursor != null && cursor.moveToFirst()) {
                    do {
                        String number = cursor.getString(
                                cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                        );

                        jsonArray.put(
                                new JsonGenerator()
                                        .put("name", name)
                                        .put("tel", number)
                                        .gen()
                        );
                    } while (cursor.moveToNext());
                }

            } while (data.moveToNext());
        }
        result = new JsonGenerator()
                .put("list", jsonArray)
                .gen();

        if (listener != null) {
            listener.success(result);
        }

        Log.d(TAG, "onLoadFinished: result =n" + result.toString());
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }

    public void setQueryListener(QueryListener listener) {
        this.listener = listener;
    }

    public interface QueryListener {
        void success(JSONObject object);
    }

}

BEFORE YOU GO

YOU'VE BEEN SELECTED FOR A GIFT

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Related Examples

One thought on “Android Contacts Example

  1. (It’s very urgent, therefore we kindly ask you to forward this email to your CEO. Thanks)

    Dear CEO,

    This email is from China domain name registration center, which mainly deal with the domain name registration in China. On 26-05-2021, we received an application from Hongsheng Ltd requested “camposha” as their internet keyword and China (CN) domain names (camposha.cn, camposha.com.cn, camposha.net.cn, camposha.org.cn). But after checking it, we find this name conflict with your company name or trademark. In order to deal with this matter better, it’s necessary to send this message to your company and confirm whether this company is your distributor or business partner in China?

    Best Regards
    Wade Liu | Service & Operations Manager
    China Registry (Head Office)
    http://www.chinaregistry.com.cn
    Tel: +86-02161918696
    Fax: +86-02161918697
    Mob: +86-13816428671
    6012, Xingdi Building, No. 1698 Yishan Road, Shanghai 201103, China

Leave a Reply

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

*

code