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