I am trying to get all contacts which have mobile numbers. I am able to fetch the contacts.But the problem is it gives me duplicate contacts.same phone number comes two times.
I used the following code to get contacts.
public static List<RawContact> getAllContacts(Context context,Account account){
Log.d(TAG, "*** Looking for local contacts with mobile number!!");
String phoneNumber = null;
String email = null;
int numberOfContacts = 0;
List<RawContact> newContacts = new ArrayList<RawContact>();
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
List<RawContact> localNewContacts = new ArrayList<RawContact>();
final ContentResolver contentResolver = context.getContentResolver();
final Cursor cursor = contentResolver.query(CONTENT_URI,
null,
null,
null,
null);
if(cursor.getCount()>0){
numberOfContacts = 0;
Log.d(TAG, "*** Looking for local contacts "+cursor.getCount());
while(cursor.moveToNext()){
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
final long rawContactId = cursor.getLong(DirtyQuery.COLUMN_RAW_CONTACT_ID);
if (hasPhoneNumber > 0) {
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'google' "+" AND "+ Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
Log.d(TAG,"Phone number is: "+phoneNumber);
RawContact rawContact = getRawContact(context, rawContactId);
Log.d(TAG, "Contact Name: " + rawContact.getBestName());
localNewContacts.add(rawContact);
}phoneCursor.close();
}
numberOfContacts++;
Log.d(TAG, "numberOfContacts updated: "+numberOfContacts);
}
}
return localNewContacts;
}
How to solve this issue