Skip to content Skip to sidebar Skip to footer

How To Get Non Duplicated Phone Numbers From Android Contacts Content Provider

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 us

Solution 1:

You're getting duplicate contacts because you're actually reading RawContacts, not contacts. Multiple RawContacts can and will contain info about a single person represented by a single Contact.

You need a single query over the Phones table, and organize the data using a HashMap from CONTACT_ID to Contact info, so you won't get duplicates.

The Contacts DB is organized in three main tables:

  1. Contacts - each entry represents one contact, and groups together one or more RawContacts
  2. RawContacts - each entry represents data about a contact that was synced in by some SyncAdapter (e.g. Whatsapp, Google, Facebook, Viber), this groups multiple Data entries
  3. Data - The actual data about a contact, emails, phones, etc. each line is a single piece of data that belongs to a single RawContact

You're trying to make a query on the Contacts table, with projection of fields from the Data table, you can't do that.

You can use something like the following code, just convert the HashMap to work with your ContactModel object:

Map<Long, List<String>> contacts = newHashMap<Long, List<String>>();

String[] projection = { Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3 };
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "')";
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);

while (cur != null && cur.moveToNext()) {
    long id = cur.getLong(0);
    String name = cur.getString(1);
    String mime = cur.getString(2); // type of data (e.g. "phone")String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
    int type = cur.getInt(4); // a numeric value representing type: e.g. home / office / personalString label = cur.getString(5); // a custom label in case type is "TYPE_CUSTOM"String labelStr = Phone.getTypeLabel(getResources(), type, label);
    Log.d(TAG, "got " + id + ", " + name + ", " + kind + " - " + data + " (" + labelStr + ")");

    // add info to existing list if this contact-id was already found, or create a new list in case it's newList<String> infos;
    if (contacts.containsKey(id)) {
        infos = contacts.get(id);
    } else {
        infos = newArrayList<String>();
        infos.add("name = " + name);
        contacts.put(id, infos);
    }
    infos.add(kind + " = " + data + " (" + labelStr + ")");
}

Post a Comment for "How To Get Non Duplicated Phone Numbers From Android Contacts Content Provider"