2016-03-30 9 views
0

In der Vergangenheit hat der folgende Code alle Kontakte auf einem Telefon erfolgreich erhalten. Unter Android 6.0 werden jetzt alle Kontakte doppelt nacheinander abgerufen. was ich nicht will.Android-Abfrage für Kontakte gibt die gleiche Nummer zweimal zurück?

ArrayList<PersonalContact> allContacts = new ArrayList<>(); 

    Cursor personalContacts = getContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, 
    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); 

    if (personalContacts != null && personalContacts.moveToFirst()) 
    { 
     do 
     { 
      String name = personalContacts.getString(personalContacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); 
      String number = personalContacts.getString(personalContacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 

      //This if statement is my current hack-y fix to this. 
      if(allContacts.size() < 1 || !allContacts.get(allContacts.size() - 1).getRawPhoneNumber().equals(number)) 
       allContacts.add(new PersonalContact(name, number)); 
     } 
     while (personalContacts.moveToNext()); 
    } 

    if (personalContacts != null) 
     personalContacts.close(); 

    return allContacts; 

Wie bekomme ich nur jeden Kontakt einmal?

Antwort

1

wird eine einfache und bessere Lösung nur eine hashmap zu benutzen, um Dubletten zu entfernen

ArrayList<PersonalContact> allContacts = new ArrayList<>(); 

    Cursor personalContacts = getContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, 
    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); 

    if (personalContacts != null && personalContacts.moveToFirst()) 
    { 
     do 
     { 
      String name = personalContacts.getString(personalContacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); 
      String number = personalContacts.getString(personalContacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 

    String normalizedNumber = number.replaceAll(" ","").replaceAll("-", ""); 
      if(duplicates.get(normalizedNumber)) 
       return; 
      duplicates.put(normalizedNumber,true); 


      allContacts.add(new PersonalContact(name, number)); 
     } 
     while (personalContacts.moveToNext()); 
    } 

    if (personalContacts != null) 
     personalContacts.close(); 

    return allContacts;