Java 仅从号码中获取联系人姓名
假设我有一个编辑文本和一个按钮。在编辑文本中,您将键入一个号码,然后当您点击按钮时,它将显示联系人信息或返回该联系人的姓名 我尝试过各种各样的方法,但运气不佳。我成功地做到了最远的一个是以下。。。但我没能把名字还给你Java 仅从号码中获取联系人姓名,java,android,eclipse,cursor,contacts,Java,Android,Eclipse,Cursor,Contacts,假设我有一个编辑文本和一个按钮。在编辑文本中,您将键入一个号码,然后当您点击按钮时,它将显示联系人信息或返回该联系人的姓名 我尝试过各种各样的方法,但运气不佳。我成功地做到了最远的一个是以下。。。但我没能把名字还给你 Cursor phoneCursor = null; contactList = new HashMap<String,String>(); try{ Uri uContactsUri = ContactsContract.CommonDat
Cursor phoneCursor = null;
contactList = new HashMap<String,String>();
try{
Uri uContactsUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String strProjection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
phoneCursor = getContentResolver().query(uContactsUri, null, null, null, strProjection);
phoneCursor.moveToFirst();
String name = "";
String phoneNumber = "";
int nameColumn = phoneCursor.getColumnIndex(Phone.DISPLAY_NAME);
int phoneColumn = phoneCursor.getColumnIndex(Phone.NUMBER);
phoneCursor.moveToNext();
}
}
catch(Exception e){
Log.e("[SmsMain] getContactData", e.toString());
}
finally{
if(phoneCursor != null){
phoneCursor.close();
phoneCursor = null;
}
}
}
cursorphonecursor=null;
contactList=newHashMap();
试一试{
Uri uContactsUri=ContactsContract.commondatatypes.Phone.CONTENT\u Uri;
String strproject=contacts contract.commondatatypes.Phone.DISPLAY\u NAME;
phoneCursor=getContentResolver().query(uContactsUri,null,null,null,strProject);
phoneCursor.moveToFirst();
字符串名称=”;
字符串phoneNumber=“”;
int nameColumn=phoneCursor.getColumnIndex(Phone.DISPLAY\u NAME);
int phoneColumn=phoneCursor.getColumnIndex(Phone.NUMBER);
phoneCursor.moveToNext();
}
}
捕获(例外e){
Log.e(“[SmsMain]getContactData”,e.toString());
}
最后{
如果(phoneCursor!=null){
phoneCursor.close();
phoneCursor=null;
}
}
}
为此,您需要使用优化的PhoneLookup提供程序,如前所述
Uri=Uri.withAppendedPath(PhoneLookup.CONTENT\u FILTER\u Uri,Uri.encode(phoneNumber));
Cursor Cursor=resolver.query(uri,新字符串[]{PhoneLookup.DISPLAY_NAME},null,null,null)
有关更多详细信息,请参阅此使用以下方法获取联系人姓名,如果号码不存在,则返回相同的号码,而不是姓名
private String getContactNameFromNumber(String number) {
// define the columns I want the query to return
String[] projection = new String[] {
Contacts.Phones.DISPLAY_NAME,
Contacts.Phones.NUMBER };
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(number));
// query time
Cursor c = getContentResolver().query(contactUri, projection, null,
null, null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(Contacts.Phones.DISPLAY_NAME));
return name;
}
// return the original number if no match was found
return number;
}