How to programmatically delete a particular android contacts Group?
I tried this,
Issue using Contact Group delete on Android
not working to me. Please tell me any ideas or suggestions. It is really help to me.
Advance Thanks!!!
I find a way to delete a group properly. You need to get the id of the group you want to remove with an appropriate query, and then you can delete this group with this id and the Groups.CONTENT_URI.
I post an example below (just adapt it to your code).
// First get the id of the group you want to remove
long groupId = null;
Cursor cursor = mContext.getContentResolver.query(Groups.CONTENT_URI,
new String[] {
Groups._ID
}, Groups.TITLE + "=?", new String[] {
yourGroupTitle // Put here the name of the group you want to delete
}, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
groupId = cursor.getLong(0);
}
} finally {
cursor.close();
}
}
// Then delete your group
ArrayList<ContentProviderOperation> mOperations = new ArrayList<ContentProviderOperation>();
// Build the uri of your group with its id
Uri uri = ContentUris.withAppendedId(Groups.CONTENT_URI, groupId).buildUpon()
.appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true")
.build();
ContentProviderOperation.Builder builder = ContentProviderOperation.newDelete(uri);
mOperations.add(builder.build());
// Then apply batch
try {
mContext.getContentResolver().applyBatch(ContactsContract.AUTHORITY, mOperations);
} catch (Exception e) {
Log.d("########## Exception :", ""+e.getMessage());
}
Hope it will be helpful.
First find all contact-ids having a specific group id. Then creating a ContentProviderOperation for each contact to be deleted, and last apply the list of delete operations.
private void deletaAllInGroup(Context context, long groupId)
throws RemoteException, OperationApplicationException{
String where = String.format("%s = ?", GroupMembership.GROUP_ROW_ID);
String[] whereParmas = new String[] {Long.toString(groupId)};
String[] colSelection = new String[] {Data.CONTACT_ID};
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
colSelection,
where,
whereParmas,
null);
ArrayList<ContentProviderOperation> operations =
new ArrayList<ContentProviderOperation>();
// iterate over all contacts having groupId
// and add them to the list to be deleted
while(cursor.moveToNext()){
String where = String.format("%s = ?", RawContacts.CONTACT_ID);
String[] whereParams = new String[]{Long.toString(cursor.getLong(0))};
operations.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)
.withSelection(where, whereParams)
.build());
}
context.getContentResolver().applyBatch(
ContactsContract.AUTHORITY, operations );
}
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