Get contact name?

2019-01-12 08:14发布

I want to get the contact name, but I'm not able to. After looking at this answer, I tried to get the name using family, given, and display, but nothing worked

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PICK_CONTACT && resultCode == RESULT_OK) {
            Uri contactUri = data.getData();
            Cursor cursor = getContentResolver().query(contactUri, null, null, null, null);
            cursor.moveToFirst(); //Move to first row...I actually dont know why this part is necessary, but I get an error without it... 
            int NumberColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); //Int column is the column of the numbers
            int NameColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
            String contactNumber = cursor.getString(NumberColumn);
            String contactName = cursor.getString(NameColumn);
            Toast.makeText(MainActivity.this, ""+ contactNumber +"" +contactName, Toast.LENGTH_SHORT).show();

        }

/

public void addContact(View v){ //OnClick listener to launch contact picker
    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
    startActivityForResult(intent, PICK_CONTACT);
}

1条回答
贪生不怕死
2楼-- · 2019-01-12 08:42

Try below code for getting contact of specific number

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CODE_PICK_CONTACTS && resultCode == RESULT_OK) {
        Log.d(TAG, "Response: " + data.toString());
        uriContact = data.getData();

        retrieveContactName();

    }
}

 private void retrieveContactName() {

        String contactName = null;

        // querying contact data store
        Cursor cursor = getContentResolver().query(uriContact, null, null, null, null);

        if (cursor.moveToFirst()) {

            // DISPLAY_NAME = The display name for the contact.
            // HAS_PHONE_NUMBER =   An indicator of whether this contact has at least one phone number.

            contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        }

        cursor.close();

        Log.d(TAG, "Contact Name: " + contactName);

    }

More detail refer below link https://tausiq.wordpress.com/2012/08/23/android-get-contact-details-id-name-phone-photo/

查看更多
登录 后发表回答