我试图在Android上获取与给定电话号码相关联的所有联系人姓名。
public void getContactName(Context context, String phoneNumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = context.getContentResolver().query(uri, new String[]{
ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String contactName = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME));
String contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
System.out.println("ID : " + contactId + " Name : " + contactName);
}
cursor.close();
}
}
但是我得到了重复的值
10-02 16:47:06.585 23359-23359/? I/System.out﹕ ID : 3480 Name : Issac
10-02 16:47:06.585 23359-23359/? I/System.out﹕ ID : 3480 Name : Issac
10-02 16:47:06.585 23359-23359/? I/System.out﹕ ID : 3401 Name : Ann
10-02 16:47:06.585 23359-23359/? I/System.out﹕ ID : 2819 Name : Sam
10-02 16:47:06.585 23359-23359/? I/System.out﹕ ID : 3480 Name : Issac
10-02 16:47:06.585 23359-23359/? I/System.out﹕ ID : 3480 Name : Issac
10-02 16:47:06.585 23359-23359/? I/System.out﹕ ID : 2819 Name : Sam
代码有什么问题吗?如何通过电话号码获取所有联系人姓名?
答案 0 :(得分:0)
我真的不知道为什么光标会多次返回相同的值。为了获得唯一值,我将id存储在arraylist中,它只包含唯一值。然后通过循环联系ID我可以获得联系人详细信息
public void getContactName(Context context, String phoneNumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = context.getContentResolver().query(uri,
new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID},null, null, null);
List<String> listIds = new ArrayList<String>(); //Arraylist to hold the unique ids
if (cursor != null) {
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
if(!listIds.contains(contactId))
listIds.add(contactId); //adding unique id to arraylist
}
//pass unique ids to get contact names
for (int i = 0; i < listIds.size(); i++) {
String newId = listIds.get(i);
Cursor cursorDetails = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{newId}, null);
if (cursorDetails != null) {
if (cursorDetails.moveToFirst()) {
String contactName = cursorDetails.getString(cursorDetails.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME));
System.out.println("ID : " + newId + " Name : " + contactName + " Number : " + phoneNumber);
}
cursorDetails.close();
}
}
cursor.close();
}
}
Logcat输出:
10-03 12:24:08.161 6306-6306/? I/System.out: ID : 3480 Name : Issac
10-03 12:24:08.161 6306-6306/? I/System.out: ID : 3401 Name : Ann
10-03 12:24:08.171 6306-6306/? I/System.out: ID : 2819 Name : Sam