I try the following code to remove contact with a specified number:
private void removeContact(Context context, String phone) { //context.getContentResolver().delete(Contacts.Phones.CONTENT_URI, phone, null); context.getContentResolver().delete(Contacts.Phones.CONTENT_URI, Contacts.PhonesColumns.NUMBER+"=?", new String[] {phone}); }
But I get this exception:
java.lang.UnsupportedOperationException: Cannot delete that URL: content://contacts/phones at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:130) at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:110) at android.content.ContentProviderProxy.delete(ContentProviderNative.java:362) at android.content.ContentResolver.delete(ContentResolver.java:386)
Can you please tell me how to fix my problem?
Thank you.
You can delete a file by using delete() method. For that first you need to create a File reference in your code by specifying the path of the file as argument, then call delete() method to delete the file.
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!
This is all we need. To delete Contact with phone number and name given
public static boolean deleteContact(Context ctx, String phone, String name) { Uri contactUri = Uri.withAppendedPath(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(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 true; } } while (cur.moveToNext()); } } catch (Exception e) { System.out.println(e.getStackTrace()); } finally { cur.close(); } return false; }
And remind to add read/write contact permission
<uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With