I am working on Unit Tests for my Android app, and I do a lot with contacts. I need to insert contacts into Android content providers and delete them after running my tests. The problem is that they are not actually deleted:
Insert:
ArrayList<ContentProviderOperation> contactOps = new ArrayList<ContentProviderOperation>(); int backRefIndex = 0; Random r = new Random(); contactOps.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null) .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null) .build()); contactOps.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRefIndex) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "Sample Name" + r.nextInt()) .build()); contactOps.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRefIndex) .withValue(ContactsContract.CommonDataKinds.Phone.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "020" + r.nextInt()) .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, r.nextInt(20) .build()); try { ContentProviderResult[] result = context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, contactOps); } catch (Exception e) { e.printStackTrace(); }
Removal Method 1 (returns the number of raw contacts, but they are not actually deleted):
int deletedRawContacts = context.getContentResolver().delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.RawContacts._ID + " >= ?", new String[]{"0"});
Removal Method 2 (same result as Removal Method 1, but different approach):
private static int deleteAllRawContacts(Context context) { ContentResolver cr = context.getContentResolver(); Cursor cur = cr.query(ContactsContract.RawContacts.CONTENT_URI, null, null, null, null); int count = 0; while (cur.moveToNext()) { try { String contactId = cur.getString(cur.getColumnIndex(ContactsContract.RawContacts._ID)); count += cr.delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.RawContacts._ID + " = ?", new String[]{contactId}); } catch (Exception e) { System.out.println(e.getStackTrace()); } } return count; }
The delete method for contacts works, but the delete method for Raw Contacts returns a false value. He will โtellโ me that he deleted all the contacts, but when I run my next test case, the old Raw Contacts can still be found (that is, the number of inserted contacts or real contacts is incorrect). Note. All tests are performed on the Android emulator.
Any ideas how to solve this?
I saw a similar question: How to delete a contact? - but the solution does not seem to solve the problem.