您正在为每个联系人的每部电话打印这些“FetchContacts”日志,因此,如果某个联系人为她存储了多个电话,您将看到它被打印多次(即使是相同的电话号码)。
如果您安装了像 Whatsapp 这样的应用程序,那么您几乎总是会看到每个联系人的所有电话号码都是重复的,从而导致每个联系人多次打印这些日志。
此外,这是一种通过手机获取联系人的缓慢而痛苦的方式。
相反,您可以直接通过 Phones.CONTENT_URI 查询并获取数据库中的所有电话,并通过 Contact-ID 将它们映射到联系人:
Map<String, List<String>> contacts = new HashMap<String, List<String>>();
String[] projection = { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor cur = cr.query(Phone.CONTENT_URI, projection, null, null, null);
while (cur != null && cur.moveToNext()) {
long id = cur.getLong(0); // contact ID
String name = cur.getString(1); // contact name
String data = cur.getString(2); // the actual info, e.g. +1-212-555-1234
Log.d(TAG, "got " + id + ", " + name + ", " + data);
// add info to existing list if this contact-id was already found, or create a new list in case it's new
String key = id + " - " + name;
List<String> infos;
if (contacts.containsKey(key)) {
infos = contacts.get(key);
} else {
infos = new ArrayList<String>();
contacts.put(key, infos);
}
infos.add(data);
}
// contacts will now contain a mapping from id+name to a list of phones.
// you can enforce uniqueness of phones while adding them to the list as well.