Showing some contacts multiple times in my App from phone book

前端 未结 2 1786
生来不讨喜
生来不讨喜 2021-01-28 05:33

I\'m getting same contact three or two times in my app this happening with some contacts not with every contacts. In my app everything is working as expected but when clicking o

相关标签:
2条回答
  • 2021-01-28 06:22

    You're printing those "FetchContacts" logs for per contact per phone, so if a contact has multiple phones stored for her you'll see it printed multiple times (even if it's the same phone number).

    If you have an app like Whatsapp installed, then almost always you'll see all phone number duplicated for each contact causing those logs to be printed more then once per contact.

    Also, that's a slow and painful way of getting contacts w/ phones. Instead you can simply query directly over Phones.CONTENT_URI and get all phones in the DB, and map them out into contacts by 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.
    
    0 讨论(0)
  • 2021-01-28 06:28

    Get rid of

    while (cur != null && cur.moveToNext()) { 
    

    Change it to

    if(cur.moveToFirst()){
    list.clear();
    
    0 讨论(0)
提交回复
热议问题