How to select multiple contacts from the phone using checkboxes

android, android-contacts

Solution

You will have to read the Contacts programmatically and display them in a `ListView` in your `Activity`. Use `CheckBox`s in the `ListView` items and allow multiple items to be selected. Find a simple example/tutorial for a `ListView` and start from there.

There are several reasons why it is better to create a custom `ListView` rather than using `Intent(Intent.ACTION_GET_CONTENT);`:

- There may not be a way to select multiples as you have requested.

- Even if you find a way to select multiples, it will be different on every OS version and device, and might not work on all of them.

- If there are multiple applications installed on any device that can handle `ACTION_GET_CONTENT`, then a chooser will be presented to the user and he will have to select one of those. The user's selection may not support selecting multiple contacts.

Here is an example that reads your system contacts:

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null); 
while (cursor.moveToNext()) {
    String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
    String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); 
    String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
    if("1".equals(hasPhone) || Boolean.parseBoolean(hasPhone)) { 
        // You know it has a number so now query it like this
        Cursor phones = myActivity.getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null); 
        while (phones.moveToNext()) { 
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            int itype = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));

            final boolean isMobile =
                itype == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE ||
                itype == ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE;

            // Do something here with 'phoneNumber' such as saving into 
            // the List or Array that will be used in your 'ListView'.

        } 
        phones.close();
    }
}

Problem

I am trying to select contacts available from the phone programmatically and I am using the below code ``` Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE); startActivityForResult(intent, 1); ``` However the question is How can I select multiple contacts at a time by using a checkbox in the contacts page?

Original source