0

So I've written a query to extract the WhatsApp contacts of a phone. My initial query goes like this:

Cursor c = con.getContentResolver().query(
        ContactsContract.RawContacts.CONTENT_URI,
        new String[]{ContactsContract.RawContacts.CONTACT_ID, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY},
        ContactsContract.RawContacts.ACCOUNT_TYPE + "= ?",
        new String[]{"com.whatsapp"},
        null
    );

ArrayList<String> myWhatsappContacts = new ArrayList<String>();
int contactNameColumn = c.getColumnIndex(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY);

while (c.moveToNext()) {
    // You can also read RawContacts.CONTACT_ID to read the
    // ContactsContract.Contacts table or any of the other related ones.
    myWhatsappContacts.add(c.getString(contactNameColumn));
}

The purpose of this is to find out how many WhatsApp contacts the phone has at any one time. When I do:

Log.i("WhatsApp contacts found:", Integer.toString(myWhatsappContacts.size());

It should print out how many WhatsApp contacts there were into LogCat. And this works - up to a point.

Let's say for example that the number of WhatsApp contacts I have now is 101. The next phase of this little project is to delete away ALL contacts if there are more than 100 of them. In which case, we go:

if (myWhatsappContacts.size() > 100) {
    //Delete all contacts code here
}

I've tested the delete contacts code, it works. I check the contacts directory of the phone via the contacts app, and it says 0. But now when I do the query again (refer to code above), it still shows 101! What's going on?

If it helps, my DeleteContacts method is as follows:

private void deleteContact(Context ctx, String phone, String name) {
    Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
    Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
    try {
        if (cur.moveToFirst()) {
            do {
                if (cur.getString(cur.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
                    String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
                    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
                    ctx.getContentResolver().delete(uri, null, null);

                    return;
                }

            } while (cur.moveToNext());
        }

    } catch (Exception e) {
        System.out.println(e.getStackTrace());
    } finally {
        cur.close();
    }

    return;
}

What am I doing wrong? Is my DeleteContacts code faulty? Or is the query itself faulty?

Riajur Rahman
  • 1,976
  • 19
  • 28
Wakka02
  • 1,491
  • 4
  • 28
  • 44

0 Answers0