获取联系人姓名?
Posted
技术标签:
【中文标题】获取联系人姓名?【英文标题】:Get contact name? 【发布时间】:2016-05-07 23:23:32 【问题描述】:我想获取联系人姓名,但无法获取。在查看this answer 之后,我尝试使用family、given 和display 来获取名称,但没有任何效果
@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】:尝试以下代码以获取特定号码的联系方式
@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);
更多详情请参考以下链接https://tausiq.wordpress.com/2012/08/23/android-get-contact-details-id-name-phone-photo/
【讨论】:
为什么是if (cursor.moveToFirst())
?谢谢]
我认为我们只有一个条目,这就是我们使用光标 movetofirst 的原因。首先它会检查光标是否为空,如果不是,它将返回数据
你能得到电话号码的名字吗?
否,因为它与我在问题中提供的代码相同。
你查过号码有名字吗?以上是关于获取联系人姓名?的主要内容,如果未能解决你的问题,请参考以下文章