Android:使用ContactsContract.CommonDataKinds.Phone检索联系人时重复联系人数据 [英] Android : Duplicate contact data while retrieving contacts using ContactsContract.CommonDataKinds.Phone
问题描述
我浏览了很多帖子,但没有找到有效甚至正确回答问题的答案.我最接近的是在将联系人信息加载到Listview时如何避免重复的联系人姓名(数据)?,但这会产生过多的开销.有没有更简单或更有效的方法来解决这个问题?
I have gone through a lot of posts but didn't find any answer that answers the question efficiently or even correctly. The closest I came was this How to avoid duplicate contact name (data ) while loading contact info to listview? but this has too much overhead. Is there any simpler or more efficient way to solve this?
推荐答案
我遇到了同样的问题:我正在获取重复的电话号码.我通过为每个光标条目获取归一化的数字并使用HashSet
跟踪已找到的数字来解决此问题.试试这个:
I had the same problem you had: I was getting duplicate phone numbers. I solved this problem by obtaining the normalized number for each cursor entry and using a HashSet
to keep track of which numbers I'd already found. Try this:
private void doSomethingForEachUniquePhoneNumber(Context context) {
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
//plus any other properties you wish to query
};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null);
} catch (SecurityException e) {
//SecurityException can be thrown if we don't have the right permissions
}
if (cursor != null) {
try {
HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();
int indexOfNormalizedNumber = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER);
int indexOfDisplayName = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexOfDisplayNumber = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (cursor.moveToNext()) {
String normalizedNumber = cursor.getString(indexOfNormalizedNumber);
if (normalizedNumbersAlreadyFound.add(normalizedNumber)) {
String displayName = cursor.getString(indexOfDisplayName);
String displayNumber = cursor.getString(indexOfDisplayNumber);
//haven't seen this number yet: do something with this contact!
} else {
//don't do anything with this contact because we've already found this number
}
}
} finally {
cursor.close();
}
}
}
这篇关于Android:使用ContactsContract.CommonDataKinds.Phone检索联系人时重复联系人数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!