我正在开发一个应用程序,我必须从联系人中搜索数字并将该联系人添加到我的编辑文本中。我写了一些代码转到联系人,但没有添加编辑文本,请告诉我代码中的任何错误
我的代码
searchBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent,1);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_OK){
Uri contactData = data.getData();
Cursor cursor = managedQuery(contactData, null, null, null, null);
cursor.moveToFirst();
String number = cursor.getString(cursor.getColumnIndexOrThrow
(ContactsContract.CommonDataKinds.Phone.NUMBER));
//contactName.setText(name);
ephoneNumber.setText(number);
//contactEmail.setText(email);
}
}
答案 0 :(得分:4)
您可以使用ContentResolver
执行此操作。调用此方法以获取contact
名称:
public String getContactDisplayNameByNumber(String number) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String name = "?";
ContentResolver contentResolver = getContentResolver();
Cursor contactLookup = contentResolver.query(uri, new String[] {BaseColumns._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null);
try {
if (contactLookup != null && contactLookup.getCount() > 0) {
contactLookup.moveToNext();
name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
//String contactId = contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
return name;
}
此方法将从联系人列表中返回所需号码的名称。代码引用是question
答案 1 :(得分:0)
您可以获取姓名或号码
// fetch contact name from phone directory
public String fetchNamePhone(String number){
String numberName= null;
/// number is the phone number
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.encode(number));
String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
Cursor c = getContentResolver().query(lookupUri, mPhoneNumberProjection, null, null,null);
try {
if(c.moveToFirst()){
return number;
// numberName = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
}
else{
number = "";
}
} catch (Exception e) {
// TODO: handle exception
}
return number;
}
调用此函数后,如果大于1则检查number.length,然后编号可用,否则编号不可用