Android get phone contacts and remove duplicates

后端 未结 5 1963
天命终不由人
天命终不由人 2021-01-14 11:53

I am having an issue related to contacts. I got the phone contacts and stored them in my list object. Here\'s the code for it

  Uri uri = ContactsContract.Da         


        
5条回答
  •  有刺的猬
    2021-01-14 12:34

    Having multiple contacts using content provider/cursor loader is obvious since we are querying raw contacts list. My way of removing duplicate items is overriding hashcode and equals method. Below is my code which will avoid adding multiple contacts to the list.

    import android.os.Parcel;
    import android.os.Parcelable;
    import android.text.TextUtils;
    

    A model class contains below fields. You can modify as you need.

    private String name;
    private String number;
    private boolean isSelected;
    

    Now override the hashcode and equals method in the model class.

    @Override
    public boolean equals(Object v) {
        boolean retVal = false;
        if (v instanceof SelectableContact){
            SelectableContact ptr = (SelectableContact) v;
            if(ptr != null) {
                //We can add some regexpressions to ignore special characters or spaces but
                // this consumes a lot of memory and slows down the contact loading.
                if(!TextUtils.isEmpty(ptr.number) && !TextUtils.isEmpty(this.number) && ptr.number.equalsIgnoreCase(this.number)) {
                    retVal = true;
                }//if
            }
        }
    
        return retVal;
    }
    
    @Override
    public int hashCode() {
        int hash = 7;
        hash = 17 * hash + (this.number != null ? this.number.hashCode() : 0);
        return hash;
    }
    

    Now it is good to go. If the contents of the list items are same, it will state away reject while adding to the list. Look into below example.Let my model class be Contact.

    public class Contact implements implements Parcelable {
    
    }
    

    Once you get the contacts from contentProvider or from ContactCursor loader, perform this action.

    List contactList = new ArraList<>;
    Contact contact = new Contact();
    if(!contactList.contains(contact)) {
        //add contact to list.
    }else {
        //remove contact from list.
    }
    

    The hashcode and equals method will compare the contents of the list item before adding. If the same contents are present it will remove.

    It is good to go.

    For more information refer Why do I need to override the equals and hashCode methods in Java?

提交回复
热议问题