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.Data.CONTENT_URI;
String[] projection = {
ContactsContract.Data.CONTACT_ID,
ContactsContract.Data.DISPLAY_NAME,
ContactsContract.Data.PHOTO_ID,
ContactsContract.Data.DATA1
};
Cursor phones = getContentResolver().query(
uri, projection, ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "' AND " + ContactsContract.Data.DATA1 + "!=''", null, null);
if (phones.moveToFirst()) {
do {
long ID = phones.getLong(phones.getColumnIndex(projection[0]));
String DisplayName = phones.getString(phones.getColumnIndex(projection[1]));
String photoID = phones.getString(phones.getColumnIndex(projection[2]));
String Key = phones.getString(phones.getColumnIndex(projection[3]));
String photoURI = "null";
if(Key != null && Key.toString().trim().length() > 0 && (Key.startsWith("0") || Key.startsWith("+"))){
if (photoID != null) {
photoURI=String.valueOf(ID);;
//Console.WriteLine("*************************************> id="+ID+" uri="+photoURI.ToString());
}
ContactBean contactModel=new ContactBean(DisplayName,Key,photoID);
list.add(contactModel);
} else {
// No number!!
}
} while (phones.moveToNext());
}
I am getting all the contacts and email contacts are removed as per my requirements. My issue is i am getting all the contacts including duplicate ones. If i have a contact saved 3 times with same name and number it is getting all the three contacts. I do not want this. Is there any way to avoid this. Anything in getContactResolver query or I have to remove duplicates for my list. Any solutions or suggestions?
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.
A model class contains below fields. You can modify as you need.
Now override the hashcode and equals method in the model class.
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.
Once you get the contacts from contentProvider or from ContactCursor loader, perform this action.
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?
Use PhoneNumberUtils.compare(a, b) to filter out duplicated numbers
You can try this :
Here i have inserted data in sqlite database first and then Write select query with group by name.
Hope it helps