In Android, how to pick a contact and display it on my app?

前端 未结 6 1731
暖寄归人
暖寄归人 2020-12-21 09:28

I am a beginner to android, i am building a application in which when the user presses a button, the contacts which is stored in the mobile are shown. When he selects a cont

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-21 09:31

    Simplest way I've found to pick a contact with phone number, and show display name and the selected phone number. See also: full, executable example as gist.

    private final static int PICK_CONTACT = 0;
    
    private void pickContact() {
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
    
        // Show only contacts with phone number. (Also forces user to choose ONE 
        // phone number for a contact that has several.)
        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
    
        startActivityForResult(intent, PICK_CONTACT);
    }
    
    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);
        switch (reqCode) {
            case (PICK_CONTACT):
                if (resultCode == Activity.RESULT_OK) {
                    handleSelectedContact(data);
                }
                break;
        }
    }
    
    private void handleSelectedContact(Intent intent) {
        Uri contactUri = intent.getData();
        Cursor c = getContentResolver().query(contactUri, null, null, null, null);
        if (c.moveToFirst()) {
            String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String selectedPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.Entity.DATA1));
    
            String message = String.format("Name %s, selected phone %s", name, selectedPhone);
            Snackbar.make(contentView, message, Snackbar.LENGTH_LONG).show();
        }
        c.close();
    }
    

    If you need other fields, for example both phone number and email, check out answers in this question.

提交回复
热议问题