Nikunj
Nikunj

Reputation: 245

Delete specific contact in android

In my application, I require to delete a particular CONTACT from phone address book, but I just got only specific number deleted not whole contact, so please help me in this.

Thanks in advance.

Upvotes: 4

Views: 3019

Answers (2)

Kartik Bhatt
Kartik Bhatt

Reputation: 924

Also try this code

private void deletePhoneNumber(Uri peopleUri, String numberToDelete) {

    Uri.Builder builder = peopleUri.buildUpon();
    builder.appendEncodedPath(People.Phones.CONTENT_DIRECTORY);
    Uri phoneNumbersUri = builder.build();


    String[] mPhoneNumberProjection = { People.Phones._ID, People.Phones.NUMBER };
    Cursor cur = resolver.query(phoneNumbersUri, mPhoneNumberProjection,
                    null, null, null);

    ArrayList<String> idsToDelete = new ArrayList<String>();

    if (cur.moveToFirst()) {
            final int colId = cur.getColumnIndex(People.Phones._ID);
            final int colNumber = cur.getColumnIndex(People.Phones.NUMBER);

            do {
                    String id = cur.getString(colId);
                    String number = cur.getString(colNumber);
                    if(number.equals(numberToDelete))
                            idsToDelete.add(id);
            } while (cur.moveToNext());
    }
    cur.close();

    for (String id : idsToDelete) {
            builder.encodedPath(People.Phones.CONTENT_DIRECTORY + "/" + id);
            phoneNumbersUri = builder.build();
            resolver.delete(phoneNumbersUri, "1 = 1", null);
    }
}

Hope it helps !!

Upvotes: 1

Kartik Bhatt
Kartik Bhatt

Reputation: 924

To delete all contacts use the following code ;

ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
        null, null, null, null);
    while (cur.moveToNext()) {
        try{
            String lookupKey = cur.getString(cur.getColumnIndex(
                ContactsContract.Contacts.LOOKUP_KEY));
            Uri uri = Uri.withAppendedPath(ContactsContract.
                Contacts.CONTENT_LOOKUP_URI, lookupKey);
            System.out.println("The uri is " + uri.toString());
            cr.delete(uri, null, null);
        }
    catch(Exception e)
    {
        System.out.println(e.getStackTrace());
    }
}

To delete any specific contact modify the query

cr.delete(uri, null, null);

Hope it helps !!

Upvotes: 7

Related Questions