Shibin Francis Shibin Francis - 3 months ago 27
Android Question

How to delete a particular contact using contact id?

I am trying to delete a particular contact from phone. I can delete the full contact. How to delete a particular contact using contact id. I want to delete the full datas including firstname, last name ,phone number, email, notes, etc...

Answer

try the following code:

            final ArrayList ops = new ArrayList();
        final ContentResolver cr = getContentResolver();
        ops.add(ContentProviderOperation
                .newDelete(ContactsContract.RawContacts.CONTENT_URI)
                .withSelection(
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                + " = ?",
                        new String[] { selected_contact_IDfromlist })
                .build());
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Delete This Contact!");
        alertDialog.setMessage("Are you Sure you want to delete this contact?");
        alertDialog.setButton(getString(R.string.callLog_delDialog_yes), new DialogInterface.OnClickListener() {    // DEPRECATED
          public void onClick(DialogInterface dialog, int which) {
            try {
                cr.applyBatch(ContactsContract.AUTHORITY, ops);
                background_process();
                ops.clear();
            } catch (OperationApplicationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            } catch (RemoteException e) {
                // System.out.println(" length :"+i);
            }
                return;
        } }); 
        alertDialog.setButton2(getString(R.string.callLog_delDialog_no), (DialogInterface.OnClickListener)null);    // DEPRECATED
        try {
            alertDialog.show();
        }catch(Exception e) {
            //              Log.e(THIS_FILE, "error while trying to show deletion yes/no dialog");
        }