CHarris
CHarris

Reputation: 2793

How to delete a contact using the lookup_key of the contact

From what I've read using lookup_key is the best way to delete a contact. Each contact has a unique lookupkey, even if the contact is edited, whereas for example deleting by name or number etc...you could be deleting multiple entries.

Say if I have the lookup_key for a contact in my phonebook or sim :

String thelookupkey = 1393i2f.3789r504-2927292F4D4D2F35274949374B.2537i1272844629.1728i108

How can I delete this contact from my phone book. I know it's something like below, but not sure of the exact syntax (also, don't want to possibly ruin my phonebook while experimenting)

public void deletecontactbutton(View view) {
    context.getContentResolver().delete(ContactsContract.Contacts.CONTENT_LOOKUP_URI,
          null, thelookupkey);

}

Upvotes: 1

Views: 313

Answers (1)

CHarris
CHarris

Reputation: 2793

I'm proud to say that I wrote (Yes, ME!!!) a subroutine that does exactly what I want : that is, delete a contact (phone, number, all details associated with that contact) using the LOOKUP_KEY value :

public void deletecontactbutton(View view) {

        String thelookupkey;
        thelookupkey = "1885r1471-29373D3D572943292D4333";

//      in our cursor query let's focus on the LOOKUP_KEY column
//      this will give us all the strings in that column
        String [] PROJECTION = new String [] {  ContactsContract.Contacts.LOOKUP_KEY };

//      we're going to query all the LOOKUP_KEY strings ; that is, the unique ids of all our contacts
//      which we can find in the LOOKUP_KEY column of the CONTENT_URI table
        Cursor cur = getContentResolver().query
                (ContactsContract.Contacts.CONTENT_URI, PROJECTION, null, null, null);

        try {
            if (cur.moveToFirst()) {
                do {
                    if
//               If a LOOKUP_KEY value is equal to our look up key string..
                 (cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)).equalsIgnoreCase(thelookupkey)) {
//               then delete that LOOKUP_KEY value, including all associated details, like number, name etc...
                        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, thelookupkey);
                        getContentResolver().delete(uri, null, null);
                    }

                } while (cur.moveToNext());
            }
//      deal with any errors, should they arise
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        } finally {
//            finally, close the cursor
            cur.close();
        }

    }

Upvotes: 1

Related Questions