Android get phone contacts and remove duplicates

我的未来我决定 提交于 2019-12-01 11:27:43

You can try this :

        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
        String lastnumber = "0";

        if (cur.getCount() > 0)
        {
            while (cur.moveToNext())
            {
                String number = null;
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
                {
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]
                    { id }, null);
                    while (pCur.moveToNext())
                    {
                        number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        Log.e("lastnumber ", lastnumber);
                        Log.e("number", number);

                        if (number.equals(lastnumber))
                        {

                        }
                        else
                        {
                            lastnumber = number;

                            Log.e("lastnumber ", lastnumber);
                            int type = pCur.getInt(pCur.getColumnIndex(Phone.TYPE));
                            switch (type)
                            {
                                case Phone.TYPE_HOME:
                                    Log.e("Not Inserted", "Not inserted");
                                    break;
                                case Phone.TYPE_MOBILE:

                                    databaseHandler.insertContact(id, name, lastnumber, 0);
                                    break;
                                case Phone.TYPE_WORK:
                                    Log.e("Not Inserted", "Not inserted");
                                    break;
                            }

                        }

                    }
                    pCur.close();
                }

            }
        }

Here i have inserted data in sqlite database first and then Write select query with group by name.

Hope it helps

Use PhoneNumberUtils.compare(a, b) to filter out duplicated numbers

val contacts = ArrayList<MyContact>()
val uniqueMobilePhones = ArrayList<String>()
                while (cursorPhones.moveToNext()) {
                    val displayName = cursorPhones.getString(cursorPhones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
                    val number = cursorPhones.getString(cursorPhones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
                    val convertedNumber = convert(telman, number)
                    var duplicate = false
                    uniqueMobilePhones.forEach { addedNumber ->
                        if (PhoneNumberUtils.compare(addedNumber, number)) {
                            duplicate = true
                        }
                    }

                    if (!duplicate) {
                        uniqueMobilePhones.add(number)
                        contacts.add(MyContact(displayName, number, convertedNumber.replace(Regex("[ -+()]"), "")))
                    }
                }
 String lastnumber = "0";
    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, Constants.PROJECTION, null, null, null);
    if (cursor != null) {
        try {
            final int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            final int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            String name, number;
            while (cursor.moveToNext()) {
                name = cursor.getString(nameIndex);
                number = cursor.getString(numberIndex).trim();
                number = number.replaceAll("\\s", "");
                if (number.equals(lastnumber)) {

                } else {
                    lastnumber = number;
                    Contact contact = new Contact();
                    contact.name = name;
                    contact.phone = number;
                    mContactList.add(contact);
                    if (adapter != null)
                        adapter.notifyDataSetChanged();
                    System.out.println("ContactFragment.readContact ==>" + name);
                }
            }
        } finally {
            cursor.close();
        }
    }

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<Contact> 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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!