Example usage for android.content ContentProviderOperation newDelete

List of usage examples for android.content ContentProviderOperation newDelete

Introduction

In this page you can find the example usage for android.content ContentProviderOperation newDelete.

Prototype

public static Builder newDelete(Uri uri) 

Source Link

Document

Create a Builder suitable for building a delete ContentProviderOperation .

Usage

From source file:com.nononsenseapps.feeder.model.RssSyncHelper.java

/**
 * Remove the designated feed from local storage. Adds the delete to the
 * list of operations, to be committed with applyBatch.
 *
 * @param context/*from   w ww.j  a  v  a 2 s.  c  o  m*/
 * @param operations
 * @param delete
 */
public static void syncDeleteBatch(final Context context, final ArrayList<ContentProviderOperation> operations,
        final BackendAPIClient.Delete delete) {
    operations.add(ContentProviderOperation.newDelete(FeedSQL.URI_FEEDS)
            .withSelection(FeedSQL.COL_URL + " IS ?", Util.ToStringArray(delete.link)).build());
}

From source file:fr.mixit.android.io.JsonHandlerApplyInterests.java

protected void deleteItemsNotFound(ContentResolver resolver) {
    for (final String lostId : ProviderParsingUtils.getLostIds(mItemIds, MixItContract.Interests.CONTENT_URI,
            MixItContract.Interests.PROJ.PROJECTION, MixItContract.Interests.PROJ.INTEREST_ID, resolver)) {
        // delete interests not found from N-N relation with session
        Uri deleteUri = MixItContract.Sessions.buildInterestsDirUri(lostId);
        ContentProviderOperation ope = ContentProviderOperation.newDelete(deleteUri).build();
        ProviderParsingUtils.addOpeAndApplyBatch(mAuthority, resolver, mBatch, false, ope);

        // and delete interests not found from N-N relation with member
        deleteUri = MixItContract.Members.buildInterestsDirUri(lostId);
        ope = ContentProviderOperation.newDelete(deleteUri).build();
        ProviderParsingUtils.addOpeAndApplyBatch(mAuthority, resolver, mBatch, false, ope);

        // and delete interests not found from interest
        deleteUri = MixItContract.Interests.buildInterestUri(lostId);
        ope = ContentProviderOperation.newDelete(deleteUri).build();
        ProviderParsingUtils.addOpeAndApplyBatch(mAuthority, resolver, mBatch, false, ope);
    }/*ww w . ja  v  a 2 s  .c o m*/
}

From source file:at.bitfire.davdroid.resource.LocalGroup.java

/**
 * Processes all groups with non-null {@link #COLUMN_PENDING_MEMBERS}: the pending memberships
 * are (if possible) applied, keeping cached memberships in sync.
 * @param addressBook    address book to take groups from
 * @throws ContactsStorageException on contact provider errors
 *//*from ww  w .j a va 2  s . c  om*/
public static void applyPendingMemberships(LocalAddressBook addressBook) throws ContactsStorageException {
    try {
        @Cleanup
        Cursor cursor = addressBook.provider.query(addressBook.syncAdapterURI(Groups.CONTENT_URI),
                new String[] { Groups._ID, COLUMN_PENDING_MEMBERS }, COLUMN_PENDING_MEMBERS + " IS NOT NULL",
                new String[] {}, null);

        BatchOperation batch = new BatchOperation(addressBook.provider);
        while (cursor != null && cursor.moveToNext()) {
            long id = cursor.getLong(0);
            Constants.log.fine("Assigning members to group " + id);

            // delete all memberships and cached memberships for this group
            batch.enqueue(new BatchOperation.Operation(ContentProviderOperation
                    .newDelete(addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI))
                    .withSelection(
                            "(" + GroupMembership.MIMETYPE + "=? AND " + GroupMembership.GROUP_ROW_ID
                                    + "=?) OR (" + CachedGroupMembership.MIMETYPE + "=? AND "
                                    + CachedGroupMembership.GROUP_ID + "=?)",
                            new String[] { GroupMembership.CONTENT_ITEM_TYPE, String.valueOf(id),
                                    CachedGroupMembership.CONTENT_ITEM_TYPE, String.valueOf(id) })
                    .withYieldAllowed(true)));

            // extract list of member UIDs
            List<String> members = new LinkedList<>();
            byte[] raw = cursor.getBlob(1);
            @Cleanup("recycle")
            Parcel parcel = Parcel.obtain();
            parcel.unmarshall(raw, 0, raw.length);
            parcel.setDataPosition(0);
            parcel.readStringList(members);

            // insert memberships
            for (String uid : members) {
                Constants.log.fine("Assigning member: " + uid);
                try {
                    LocalContact member = addressBook.findContactByUID(uid);
                    member.addToGroup(batch, id);
                } catch (FileNotFoundException e) {
                    Constants.log.log(Level.WARNING, "Group member not found: " + uid, e);
                }
            }

            // remove pending memberships
            batch.enqueue(new BatchOperation.Operation(ContentProviderOperation
                    .newUpdate(addressBook.syncAdapterURI(ContentUris.withAppendedId(Groups.CONTENT_URI, id)))
                    .withValue(COLUMN_PENDING_MEMBERS, null).withYieldAllowed(true)));

            batch.commit();
        }
    } catch (RemoteException e) {
        throw new ContactsStorageException("Couldn't get pending memberships", e);
    }
}

From source file:com.google.samples.apps.iosched.io.SessionsHandler.java

private void buildDeleteOperation(String sessionId, List<ContentProviderOperation> list) {
    Uri sessionUri = ScheduleContractHelper
            .setUriAsCalledFromSyncAdapter(ScheduleContract.Sessions.buildSessionUri(sessionId));
    list.add(ContentProviderOperation.newDelete(sessionUri).build());
}

From source file:org.muckebox.android.net.RefreshHelper.java

public static Integer refreshArtists() {
    try {/*from   w  w w.j  av  a 2 s  . com*/
        JSONArray json = ApiHelper.callApiForArray("artists");
        ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(
                json.length() + 1);

        operations.add(ContentProviderOperation.newDelete(MuckeboxProvider.URI_ARTISTS).build());

        for (int i = 0; i < json.length(); ++i) {
            JSONObject o = json.getJSONObject(i);
            operations.add(ContentProviderOperation.newInsert(MuckeboxProvider.URI_ARTISTS)
                    .withValue(ArtistEntry.SHORT_ID, o.getInt("id"))
                    .withValue(ArtistEntry.SHORT_NAME, o.getString("name")).build());
        }

        Muckebox.getAppContext().getContentResolver().applyBatch(MuckeboxProvider.AUTHORITY, operations);
    } catch (AuthenticationException e) {
        return R.string.error_authentication;
    } catch (SSLException e) {
        return R.string.error_ssl;
    } catch (IOException e) {
        Log.d(LOG_TAG, "IOException: " + e.getMessage());
        return R.string.error_reload_artists;
    } catch (JSONException e) {
        return R.string.error_json;
    } catch (RemoteException e) {
        e.printStackTrace();
        return R.string.error_reload_artists;
    } catch (OperationApplicationException e) {
        e.printStackTrace();
        return R.string.error_reload_artists;
    }

    return null;
}

From source file:cz.maresmar.sfm.utils.ActionUtils.java

/**
 * Make edits in Actions for corresponding Menu entry. These action are saved as
 * {@link ProviderContract#ACTION_SYNC_STATUS_LOCAL} then.
 * <p>//from  w  w w. j  av a  2 s. c  o m
 * Handles menu group restrictions (like one order per group), in such cases creates
 * {@link ProviderContract#ACTION_ENTRY_TYPE_VIRTUAL} actions to override the
 * {@link ProviderContract#ACTION_SYNC_STATUS_SYNCED} ones. If an action reserves nothing,
 * the action is removed.
 * </p>
 *
 * @param context    Some valid context
 * @param userUri    User Uri prefix
 * @param relativeId Relative ID of corresponding Menu entry
 * @param portalId   Portal ID of corresponding Menu entry
 * @param reserved   New amount of reserved food
 * @param offered    New amount of offered food
 */
@WorkerThread
public static void makeEdit(@NonNull Context context, @NonNull Uri userUri, long relativeId, long portalId,
        int reserved, int offered) {
    // Load the corresponding menu entry
    @ProviderContract.PortalFeatures
    int portalFeatures;
    long menuGroupId;
    int price;
    long date;
    int syncedReserved, syncedOffered, syncedTaken;
    boolean hasLocal;
    int localReserved, localOffered;
    long portalGroupId;

    Uri menuUri = Uri.withAppendedPath(userUri, ProviderContract.MENU_ENTRY_PATH);
    ArrayList<ContentProviderOperation> ops = new ArrayList<>();

    try (Cursor menuCursor = context.getContentResolver().query(menuUri, new String[] {
            ProviderContract.MenuEntry.PORTAL_FEATURES, ProviderContract.MenuEntry.GROUP_ID,
            ProviderContract.MenuEntry.PRICE, ProviderContract.MenuEntry.DATE,
            ProviderContract.MenuEntry.SYNCED_RESERVED_AMOUNT, ProviderContract.MenuEntry.SYNCED_OFFERED_AMOUNT,
            ProviderContract.MenuEntry.SYNCED_TAKEN_AMOUNT, ProviderContract.MenuEntry.LOCAL_RESERVED_AMOUNT,
            ProviderContract.MenuEntry.LOCAL_OFFERED_AMOUNT, ProviderContract.MenuEntry.PORTAL_GROUP_ID },
            ProviderContract.MenuEntry.ME_RELATIVE_ID + " = " + relativeId + " AND "
                    + ProviderContract.MenuEntry.PORTAL_ID + " = " + portalId,
            null, null)) {

        if (BuildConfig.DEBUG) {
            Assert.isOne(menuCursor.getCount());
        }

        menuCursor.moveToFirst();

        // Info
        portalFeatures = menuCursor.getInt(0);
        menuGroupId = menuCursor.getLong(1);
        price = menuCursor.getInt(2);
        date = menuCursor.getLong(3);

        // Synced
        syncedReserved = menuCursor.getInt(4);
        syncedOffered = menuCursor.getInt(5);
        syncedTaken = menuCursor.getInt(6);

        // Local
        hasLocal = !menuCursor.isNull(7);
        localReserved = menuCursor.getInt(7);
        localOffered = menuCursor.getInt(8);

        // Portal group
        portalGroupId = menuCursor.getLong(9);

        // Insert changes
        Uri actionUri = Uri.withAppendedPath(userUri, ProviderContract.ACTION_PATH);
        // Insert virtual group changes
        boolean restrictToOneOrderPerGroup = (portalFeatures
                & ProviderContract.FEATURE_RESTRICT_TO_ONE_ORDER_PER_GROUP) == ProviderContract.FEATURE_RESTRICT_TO_ONE_ORDER_PER_GROUP;

        // Delete old edits as I want something new
        if (!restrictToOneOrderPerGroup) {
            // Delete action for this menu entry
            ops.add((ContentProviderOperation.newDelete(actionUri)
                    .withSelection(ProviderContract.Action.ME_RELATIVE_ID + " = " + relativeId + " AND "
                            + ProviderContract.Action.ME_PORTAL_ID + " = " + portalId + " AND "
                            + ProviderContract.Action.SYNC_STATUS + " = "
                            + ProviderContract.ACTION_SYNC_STATUS_EDIT, null)
                    .build()));
        } else {
            // Delete actions for whole menu entry group
            ops.add(ContentProviderOperation.newDelete(actionUri)
                    .withSelection(ProviderContract.Action.ME_PORTAL_ID + " IN " + "(SELECT "
                            + DbContract.Portal._ID + " FROM " + DbContract.Portal.TABLE_NAME + " WHERE "
                            + DbContract.Portal.COLUMN_NAME_PGID + " == " + portalGroupId + " ) AND "
                            + ProviderContract.Action.SYNC_STATUS + " = "
                            + ProviderContract.ACTION_SYNC_STATUS_EDIT + " AND " + "EXISTS ( SELECT * FROM "
                            + DbContract.MenuEntry.TABLE_NAME + " WHERE " + DbContract.MenuEntry.COLUMN_NAME_PID
                            + " == " + ProviderContract.Action.ME_PORTAL_ID + " AND "
                            + DbContract.MenuEntry.COLUMN_NAME_RELATIVE_ID + " == "
                            + ProviderContract.Action.ME_RELATIVE_ID + " AND "
                            + DbContract.MenuEntry.COLUMN_NAME_DATE + " == " + date + " AND "
                            + DbContract.MenuEntry.COLUMN_NAME_MGID + " == " + menuGroupId + " )", null)
                    .build());
        }

        // Insert new edits
        if ((hasLocal && !(reserved == localReserved && offered == localOffered))
                || (!hasLocal && !(reserved == syncedReserved && offered == syncedOffered))) {
            if (restrictToOneOrderPerGroup) {
                // Sets other actions in group to zeros
                try (Cursor groupCursor = context.getContentResolver().query(menuUri, new String[] {
                        ProviderContract.MenuEntry.ME_RELATIVE_ID, ProviderContract.MenuEntry.PRICE,
                        ProviderContract.MenuEntry.STATUS, ProviderContract.MenuEntry.SYNCED_RESERVED_AMOUNT,
                        ProviderContract.MenuEntry.SYNCED_TAKEN_AMOUNT, ProviderContract.MenuEntry.PORTAL_ID },
                        ProviderContract.MenuEntry.PORTAL_ID + " IN " + "(SELECT " + DbContract.Portal._ID
                                + " FROM " + DbContract.Portal.TABLE_NAME + " WHERE "
                                + DbContract.Portal.COLUMN_NAME_PGID + " == " + portalGroupId + " ) AND "
                                + ProviderContract.MenuEntry.DATE + " = " + date + " AND "
                                + ProviderContract.MenuEntry.GROUP_ID + " = " + menuGroupId + " AND ("
                                + "(IFNULL(" + ProviderContract.MenuEntry.SYNCED_RESERVED_AMOUNT + ", 0)"
                                + " - IFNULL(" + ProviderContract.MenuEntry.SYNCED_TAKEN_AMOUNT
                                + ", 0)) > 0 OR " + "(IFNULL("
                                + ProviderContract.MenuEntry.LOCAL_RESERVED_AMOUNT + ", 0)" + " - IFNULL("
                                + ProviderContract.MenuEntry.SYNCED_TAKEN_AMOUNT + ", 0)) > 0)",
                        null, null)) {
                    if (groupCursor != null) {
                        while (groupCursor.moveToNext()) {
                            // Skip main changed row
                            if (groupCursor.getLong(0) == relativeId) {
                                continue;
                            }

                            @ProviderContract.MenuStatus
                            int status = groupCursor.getInt(2);
                            boolean canCancel = (status
                                    & ProviderContract.MENU_STATUS_CANCELABLE) == ProviderContract.MENU_STATUS_CANCELABLE;
                            boolean canUseStock = (status
                                    & ProviderContract.FEATURE_FOOD_STOCK) == ProviderContract.FEATURE_FOOD_STOCK;

                            // Insert virtual actions
                            ContentValues newAction = new ContentValues();
                            newAction.put(ProviderContract.Action.ME_RELATIVE_ID, groupCursor.getLong(0));
                            newAction.put(ProviderContract.Action.ME_PORTAL_ID, groupCursor.getLong(5));
                            newAction.put(ProviderContract.Action.SYNC_STATUS,
                                    ProviderContract.ACTION_SYNC_STATUS_EDIT);
                            newAction.put(ProviderContract.Action.ENTRY_TYPE,
                                    ProviderContract.ACTION_ENTRY_TYPE_VIRTUAL);
                            newAction.put(ProviderContract.Action.PRICE, groupCursor.getInt(1));
                            if (canCancel) {
                                newAction.put(ProviderContract.Action.RESERVED_AMOUNT, 0);
                                newAction.put(ProviderContract.Action.OFFERED_AMOUNT, 0);
                            } else {
                                newAction.put(ProviderContract.Action.RESERVED_AMOUNT, groupCursor.getInt(3));
                                newAction.put(ProviderContract.Action.OFFERED_AMOUNT, groupCursor.getInt(3));

                                Toast.makeText(context, R.string.actions_food_stock_on_restricted_to_one,
                                        Toast.LENGTH_LONG).show();
                            }
                            newAction.put(ProviderContract.Action.TAKEN_AMOUNT, groupCursor.getInt(4));

                            ops.add(ContentProviderOperation.newInsert(actionUri).withValues(newAction)
                                    .build());
                        }
                    }
                }
            }

            // Insert main edit
            ContentValues newAction = new ContentValues();
            newAction.put(ProviderContract.Action.ME_RELATIVE_ID, relativeId);
            newAction.put(ProviderContract.Action.ME_PORTAL_ID, portalId);
            newAction.put(ProviderContract.Action.SYNC_STATUS, ProviderContract.ACTION_SYNC_STATUS_EDIT);
            newAction.put(ProviderContract.Action.ENTRY_TYPE, ProviderContract.ACTION_ENTRY_TYPE_STANDARD);
            newAction.put(ProviderContract.Action.PRICE, price);
            newAction.put(ProviderContract.Action.RESERVED_AMOUNT, reserved);
            newAction.put(ProviderContract.Action.OFFERED_AMOUNT, offered);
            newAction.put(ProviderContract.Action.TAKEN_AMOUNT, syncedTaken);

            ops.add(ContentProviderOperation.newInsert(actionUri).withValues(newAction).build());
        }

        // Apply changes at once (it boost the performance)
        try {
            context.getContentResolver().applyBatch(ProviderContract.AUTHORITY, ops);
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.battlelancer.seriesguide.ui.dialogs.ListsDialogFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View layout = inflater.inflate(R.layout.list_dialog, null);

    // buttons//  w ww  .  ja  v a2 s.  c o  m
    Button dontAddButton = (Button) layout.findViewById(R.id.buttonNegative);
    dontAddButton.setText(android.R.string.cancel);
    dontAddButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    });
    Button addButton = (Button) layout.findViewById(R.id.buttonPositive);
    addButton.setText(android.R.string.ok);
    addButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // add item to selected lists
            String itemId = getArguments().getString("itemid");
            int itemType = getArguments().getInt("itemtype");
            SparseBooleanArray checkedLists = mAdapter.getCheckedPositions();

            final ArrayList<ContentProviderOperation> batch = com.uwetrottmann.androidutils.Lists
                    .newArrayList();

            for (int position = 0; position < mAdapter.getCount(); position++) {
                final Cursor listEntry = (Cursor) mAdapter.getItem(position);

                boolean wasListChecked = !TextUtils.isEmpty(listEntry.getString(ListsQuery.LIST_ITEM_ID));
                boolean isListChecked = checkedLists.get(position);

                String listId = listEntry.getString(ListsQuery.LIST_ID);
                String listItemId = ListItems.generateListItemId(itemId, itemType, listId);

                if (wasListChecked && !isListChecked) {
                    // remove from list
                    batch.add(
                            ContentProviderOperation.newDelete(ListItems.buildListItemUri(listItemId)).build());
                } else if (!wasListChecked && isListChecked) {
                    // add to list
                    ContentValues values = new ContentValues();
                    values.put(ListItems.LIST_ITEM_ID, listItemId);
                    values.put(ListItems.ITEM_REF_ID, itemId);
                    values.put(ListItems.TYPE, itemType);
                    values.put(Lists.LIST_ID, listId);
                    batch.add(ContentProviderOperation.newInsert(ListItems.CONTENT_URI).withValues(values)
                            .build());
                }
            }

            // apply ops
            try {
                DBUtils.applyInSmallBatches(getActivity(), batch);
            } catch (OperationApplicationException e) {
                Timber.e("Applying list changes failed", e);
            }

            getActivity().getContentResolver().notifyChange(ListItems.CONTENT_WITH_DETAILS_URI, null);

            dismiss();
        }
    });

    // lists list
    mListView = (ListView) layout.findViewById(R.id.list);
    /*
     * As using CHOICE_MODE_MULTIPLE does not seem to work before Jelly
     * Bean, do everything ourselves.
     */
    mListView.setOnItemClickListener(this);

    return layout;
}

From source file:edu.mit.mobile.android.demomode.Preferences.java

private void fromCfgString(String cfg) {
    final Uri cfgUri = Uri.parse(cfg);
    if ("data".equals(cfgUri.getScheme())) {
        final String[] cfgParts = cfgUri.getEncodedSchemeSpecificPart().split(",", 2);
        if (CFG_MIME_TYPE.equals(cfgParts[0])) {
            final Editor ed = mPrefs.edit();
            final ArrayList<ContentProviderOperation> cpos = new ArrayList<ContentProviderOperation>();

            // first erase everything
            cpos.add(ContentProviderOperation.newDelete(LauncherItem.CONTENT_URI).build());

            try {
                final StringEntity entity = new StringEntity(cfgParts[1]);
                entity.setContentType("application/x-www-form-urlencoded");
                final List<NameValuePair> nvp = URLEncodedUtils.parse(entity);
                for (final NameValuePair pair : nvp) {
                    final String name = pair.getName();
                    Log.d(TAG, "parsed pair: " + pair);
                    if (CFG_K_SECRETKEY.equals(name)) {
                        ed.putString(KEY_PASSWORD, pair.getValue());

                    } else if (CFG_K_APPS.equals(name)) {
                        final String[] app = pair.getValue().split(CFG_PKG_SEP, 2);
                        final ContentProviderOperation cpo = ContentProviderOperation
                                .newInsert(LauncherItem.CONTENT_URI)
                                .withValue(LauncherItem.PACKAGE_NAME, app[0])
                                .withValue(LauncherItem.ACTIVITY_NAME, app[1]).build();
                        cpos.add(cpo);/*from  w ww  .  j av  a 2 s  . c  o  m*/
                        Log.d(TAG, "adding " + cpo);
                    }
                }

                ed.commit();
                getContentResolver().applyBatch(HomescreenProvider.AUTHORITY, cpos);
            } catch (final UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (final IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (final RemoteException e) {
                // TODO Auto-generated catch block

                e.printStackTrace();
            } catch (final OperationApplicationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            Log.e(TAG, "unknown MIME type for data URI: " + cfgParts[0]);
        }

    } else {
        Log.e(TAG, "not a data URI");
    }
}

From source file:com.battlelancer.seriesguide.ui.dialogs.ManageListsDialogFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View layout = inflater.inflate(R.layout.dialog_manage_lists, container, false);

    // buttons/*w  w w .  j  a v  a 2  s .  c o  m*/
    Button dontAddButton = (Button) layout.findViewById(R.id.buttonNegative);
    dontAddButton.setText(android.R.string.cancel);
    dontAddButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    });
    Button addButton = (Button) layout.findViewById(R.id.buttonPositive);
    addButton.setText(android.R.string.ok);
    addButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // add item to selected lists
            int itemTvdbId = getArguments().getInt(InitBundle.INT_ITEM_TVDB_ID);
            int itemType = getArguments().getInt(InitBundle.INT_ITEM_TYPE);
            SparseBooleanArray checkedLists = mAdapter.getCheckedPositions();

            final ArrayList<ContentProviderOperation> batch = new ArrayList<>();

            for (int position = 0; position < mAdapter.getCount(); position++) {
                final Cursor listEntry = (Cursor) mAdapter.getItem(position);

                boolean wasListChecked = !TextUtils.isEmpty(listEntry.getString(ListsQuery.LIST_ITEM_ID));
                boolean isListChecked = checkedLists.get(position);

                String listId = listEntry.getString(ListsQuery.LIST_ID);
                String listItemId = ListItems.generateListItemId(itemTvdbId, itemType, listId);

                if (wasListChecked && !isListChecked) {
                    // remove from list
                    batch.add(
                            ContentProviderOperation.newDelete(ListItems.buildListItemUri(listItemId)).build());
                } else if (!wasListChecked && isListChecked) {
                    // add to list
                    ContentValues values = new ContentValues();
                    values.put(ListItems.LIST_ITEM_ID, listItemId);
                    values.put(ListItems.ITEM_REF_ID, itemTvdbId);
                    values.put(ListItems.TYPE, itemType);
                    values.put(Lists.LIST_ID, listId);
                    batch.add(ContentProviderOperation.newInsert(ListItems.CONTENT_URI).withValues(values)
                            .build());
                }
            }

            // apply ops
            try {
                DBUtils.applyInSmallBatches(getActivity(), batch);
            } catch (OperationApplicationException e) {
                Timber.e(e, "Applying list changes failed");
            }

            getActivity().getContentResolver().notifyChange(ListItems.CONTENT_WITH_DETAILS_URI, null);

            dismiss();
        }
    });

    // lists list
    mListView = (ListView) layout.findViewById(R.id.list);
    /*
     * As using CHOICE_MODE_MULTIPLE does not seem to work before Jelly
     * Bean, do everything ourselves.
     */
    mListView.setOnItemClickListener(this);

    return layout;
}

From source file:org.linphone.ContactsListFragment.java

private void deleteExistingContact(Contact contact) {
    String select = ContactsContract.Data.CONTACT_ID + " = ?";
    String[] args = new String[] { contact.getID() };

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
            .withSelection(select, args).build());

    try {/*from  w w  w. ja va2 s  .c  o  m*/
        getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        ContactsManager.getInstance().removeAllFriends(contact);
    } catch (Exception e) {
        Log.w(e.getMessage() + ":" + e.getStackTrace());
    }
}