How to select multiple contacts from the phone using checkboxes

前端 未结 2 1548
忘掉有多难
忘掉有多难 2021-01-02 23:47

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_C         


        
2条回答
  •  一生所求
    2021-01-03 00:45

    You will have to read the Contacts programmatically and display them in a ListView in your Activity. Use CheckBoxs 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);:

    1. There may not be a way to select multiples as you have requested.
    2. 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.
    3. 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();
        }
    }
    

提交回复
热议问题