• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Delete Contact

ibwev

Lurker
Jun 23, 2018
5
0
I am using the following code to attempt to delete a contact. I have used these two sites as references https://developer.android.com/reference/android/provider/ContactsContract.Data and https://www.dev2qa.com/how-to-update-delete-android-contacts-programmatically. My code executes but does not delete the contact from the phone. Please help me understand what I am doing wrong. If possible, I would prefer to open the users default contact app with the intended contact to delete preselected so the user can use the default contact app to delete the contact.

Code:
    public void sendRent(View view){

        String rent = rentET.getText().toString();

        if (deleteTenant){

            long dataID = getRawContactIdByName(address);
            ArrayList<ContentProviderOperation> opsDataTable = new ArrayList<ContentProviderOperation>();
            ArrayList<ContentProviderOperation> opsRawData = new ArrayList<ContentProviderOperation>();

            opsDataTable.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                    .withSelection(ContactsContract.Data._ID + "=?", new String[]{String.valueOf(dataID)})
                    .build());
            opsRawData.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                    .withSelection(ContactsContract.Data._ID + "=?", new String[]{String.valueOf(dataID)})
                    .build());

            try {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CONTACTS},MY_PERMISSION_REQUEST_CALL_PHONE);
                    return;
                }
                getContentResolver().applyBatch(ContactsContract.AUTHORITY, opsDataTable);
                getContentResolver().applyBatch(ContactsContract.AUTHORITY, opsRawData);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        BackgroundWorker bw = new BackgroundWorker(this);
        bw.execute("RentEnter", rent, address, gid);

        finish();
    }

    /* Get raw contact id by contact given name and family name.
     *  Return raw contact id.
     *  https://www.dev2qa.com/how-to-update-delete-android-contacts-programmatically/
     * */
    private long getRawContactIdByName(String contactName)
    {
        ContentResolver contentResolver = getContentResolver();

        // Query raw_contacts table by display name field ( given_name family_name ) to get raw contact id.

        // Create query column array.
        String queryColumnArr[] = {ContactsContract.RawContacts._ID};

        // Create where condition clause.
        String whereClause = ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY + " REGEXP '" + contactName + ".*'";
        //String whereClause = ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY + " REGEXP '1 abc - y u'";

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS},MY_PERMISSION_REQUEST_CALL_PHONE);
        }
        // Query raw contact id through RawContacts uri.
        Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI;

        // Return the query cursor.
        Cursor cursor = contentResolver.query(rawContactUri, queryColumnArr, whereClause, null, null);

        long rawContactId = -1;

        if(cursor!=null)
        {
            // Get contact count that has same display name, generally it should be one.
            int queryResultCount = cursor.getCount();
            // This check is used to avoid cursor index out of bounds exception. android.database.CursorIndexOutOfBoundsException
            if(queryResultCount > 0)
            {
                // Move to the first row in the result cursor.
                cursor.moveToFirst();
                // Get raw_contact_id.
                rawContactId = cursor.getLong(cursor.getColumnIndex(ContactsContract.RawContacts._ID));
            }
        }

        return rawContactId;
    }
 
I found my error. I never used ContactsContract.Data.RAW_CONTACT_ID as my selection.

Code:
            opsDataTable.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                    .withSelection(ContactsContract.Data._ID + "=?", new String[]{String.valueOf(dataID)})
                    .build());
            opsRawData.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                    .withSelection(ContactsContract.Data._ID + "=?", new String[]{String.valueOf(dataID)})
                    .build());
    }

It should have been:

Code:
    [/COLOR][/LEFT]
opsDataTable.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
        .withSelection(ContactsContract.Data._ID + "=?", new String[]{String.valueOf(dataID)})
        .build());
opsRawData.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
        .withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=?", new String[]{String.valueOf(dataID)})
        .build());

[LEFT][COLOR=rgb(55, 71, 79)]    }
[/QUOTE]

 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones