@Override protected void removeDataRows(Resource resource) { Event event = (Event) resource; pendingOperations.add( ContentProviderOperation.newDelete(syncAdapterURI(Attendees.CONTENT_URI)) .withSelection( Attendees.EVENT_ID + "=?", new String[] {String.valueOf(event.getLocalID())}) .build()); pendingOperations.add( ContentProviderOperation.newDelete(syncAdapterURI(Reminders.CONTENT_URI)) .withSelection( Reminders.EVENT_ID + "=?", new String[] {String.valueOf(event.getLocalID())}) .build()); }
public void buildCapsuleCleanup(long keepId, List<Long> duplicateIds) { // Convert the extra IDs into selection arguments String[] selectionArgs = CapsuleOperations.convertIdsToArguments(duplicateIds); String preparedStatementParams = CapsuleOperations.buildPreparedStatementParameters(duplicateIds.size()); // UPDATE operation to change all Discoveries referencing the extra IDs to instead reference the // keep ID String discoverySelection = CapsuleContract.Discoveries.CAPSULE_ID + " IN (" + preparedStatementParams + ")"; this.mOperations.add( ContentProviderOperation.newUpdate(CapsuleContract.Discoveries.CONTENT_URI) .withSelection(discoverySelection, selectionArgs) .withValue(CapsuleContract.Discoveries.CAPSULE_ID, keepId) .withYieldAllowed(true) .build()); // UPDATE operation to change all Ownerships referencing the extra IDs to instead reference the // keep ID String ownershipSelection = CapsuleContract.Ownerships.CAPSULE_ID + " IN (" + preparedStatementParams + ")"; this.mOperations.add( ContentProviderOperation.newUpdate(CapsuleContract.Ownerships.CONTENT_URI) .withSelection(ownershipSelection, selectionArgs) .withValue(CapsuleContract.Ownerships.CAPSULE_ID, keepId) .withYieldAllowed(false) .build()); // DELETE the duplicate Capsules String capsuleSelection = CapsuleContract.Capsules._ID + " IN (" + preparedStatementParams + ")"; this.mOperations.add( ContentProviderOperation.newDelete(CapsuleContract.Capsules.CONTENT_URI) .withSelection(capsuleSelection, selectionArgs) .withYieldAllowed(false) .build()); }
@Override public ArrayList<ContentProviderOperation> parse(String parser, ContentResolver resolver) throws IOException, JSONException { // TODO Auto-generated method stub Log.v("TAG", "ENTER INTO DASHBORED"); ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); ContentProviderOperation.Builder builder_delete = ContentProviderOperation.newDelete(Dashboards.CONTENT_URI); batch.add(builder_delete.build()); if (parser != null) { Gson gson = new Gson(); dashBoard = gson.fromJson(parser, Dashboard.class); final ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(Dashboards.CONTENT_URI); builder.withValue(Dashboards.PATIENT_ID, dashBoard.getPatientId()); builder.withValue(Dashboards.JSON, parser); batch.add(builder.build()); Log.v("dashboard", dashBoard.getPatientId()); Log.v("TAG", "LOADED INTO DATABASE"); } return batch; }
/** * Finds all apks from the repo we are currently updating, that belong to the specified app, and * delete them as they are no longer provided by that repo. */ @Nullable private ContentProviderOperation deleteOrphanedApks( List<App> apps, Map<String, List<Apk>> packages) { String[] projection = new String[] {ApkProvider.DataColumns.PACKAGE_NAME, ApkProvider.DataColumns.VERSION_CODE}; List<Apk> existing = ApkProvider.Helper.find(context, repo, apps, projection); List<Apk> toDelete = new ArrayList<>(); for (Apk existingApk : existing) { boolean shouldStay = false; if (packages.containsKey(existingApk.packageName)) { for (Apk newApk : packages.get(existingApk.packageName)) { if (newApk.vercode == existingApk.vercode) { shouldStay = true; break; } } } if (!shouldStay) { toDelete.add(existingApk); } } if (toDelete.size() == 0) { return null; } Uri uri = TempApkProvider.getApksUri(repo, toDelete); return ContentProviderOperation.newDelete(uri).build(); }
/** M: Wipe the records from MessageStateChange table which belong to mMailbox */ private void wipeMessageStateChanges() { Cursor c = mContentResolver.query( Message.CONTENT_URI, new String[] {MessageColumns.MESSAGE_ID}, MessageColumns.MAILBOX_KEY + "=?", new String[] {String.valueOf(mMailbox.mId)}, null); if (c == null) { LogUtils.i(Eas.BSK_TAG, "Get message cursor failed"); return; } try { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); while (c.moveToNext()) { ops.add( ContentProviderOperation.newDelete(MessageStateChange.CONTENT_URI) .withSelection( MessageChangeLogTable.MESSAGE_KEY + "=?", new String[] {c.getString(0)}) .build()); applyBatchIfNeeded(ops, MAX_OPS_PER_BATCH, false); } applyBatchIfNeeded(ops, MAX_OPS_PER_BATCH, true); } catch (RemoteException e) { LogUtils.i(Eas.BSK_TAG, "RemoteException when wipeMessageStateChanges"); } catch (OperationApplicationException e) { LogUtils.i(Eas.BSK_TAG, "OperationApplicationException when wipeMessageStateChanges"); } finally { c.close(); } }
/** * Delete the users that are present in the local content providers, but are not returned anymore * by Dailymotion. It means that these users are outdated and should not be proposed to the user. * * @return A boolean indicating if the deletion successfully occured. */ private boolean deleteOutdatedUsers() { if (mLocalUsers.size() > 0) { int count = mLocalUsers.size(); KidsLogger.i(LOG_TAG, String.format("Removing %d users from db", count)); ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(count); for (String key : mLocalUsers.keySet()) { ContentProviderOperation operation = ContentProviderOperation.newDelete(UsersProvider.CONTENT_URI) .withSelection(UserContract.DAILYMOTION_ID + "=?", new String[] {key}) .build(); ops.add(operation); } try { return mContentResolver.applyBatch(UsersProvider.AUTHORITY, ops).length == count; } catch (RemoteException e) { // Should not happen, the Content Provider is local. KidsLogger.w(LOG_TAG, "An exception occured while communicating with provider."); return false; } catch (OperationApplicationException e) { KidsLogger.w(LOG_TAG, "An operation has failed when deleting local users."); return false; } } return true; }
/** Removes all calendar entries associated with Google I/O 2013. */ private ArrayList<ContentProviderOperation> processClearAllSessions( ContentResolver resolver, long calendarId) { ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Unable to find the Calendar associated with the user. Stop here. if (calendarId == INVALID_CALENDAR_ID) { Log.e(TAG, "Unable to find Calendar for user"); return batch; } // Delete all calendar entries matching the given title within the given time period batch.add( ContentProviderOperation.newDelete(CalendarContract.Events.CONTENT_URI) .withSelection( CalendarContract.Events.CALENDAR_ID + " = ? and " + CalendarContract.Events.TITLE + " LIKE ? and " + CalendarContract.Events.DTSTART + ">= ? and " + CalendarContract.Events.DTEND + "<= ?", new String[] { Long.toString(calendarId), CALENDAR_CLEAR_SEARCH_LIKE_EXPRESSION, Long.toString(Config.CONFERENCE_START_MILLIS), Long.toString(Config.CONFERENCE_END_MILLIS) }) .build()); return batch; }
@Override protected void onHandleIntent(Intent intent) { Map<String, String> eventBody = new HashMap<>(); try { // get caller data Bundle iArgs = intent.getExtras(); // src String src = iArgs.getString(AppConstants.K.SRC.name()); eventBody.put(AppConstants.K.SRC.name(), src); // srcID String srcID = iArgs.getString(AppConstants.K.SRC_ID.name()); eventBody.put(AppConstants.K.SRC_ID.name(), srcID); String notifUID = iArgs.getString(AppConstants.K.NOTIF.name()); eventBody.put(AppConstants.K.NOTIF.name(), notifUID); if (StringUtils.isNotBlank(notifUID)) { // LOCAL UPDATE ArrayList<ContentProviderOperation> delOps = new ArrayList<>(); delOps.add( ContentProviderOperation.newDelete(SchemaNotifications.CONTENT_URI) .withSelection(SchemaNotifications.COLUMN_UID + "=?", new String[] {notifUID}) .build()); getContentResolver().applyBatch(AppConstants.API.CONTENT_AUTHORITY.getValue(), delOps); } else { return; } // REMOTE UPDATE String notifURI = StringUtils.join(new String[] {NOTIFICATIONS.getValue(), notifUID}, "/"); // body part of request Map<String, String> reqBody = new HashMap<>(); if (!Utils.isLoggedIn()) { // UNIQUE ID FOR THIS INSTALL reqBody.put(PARAMS.REF.getValue(), Utils.uniqueID()); } ReqSetBody req = new ReqSetBody(); req.setToken(Utils.getAppToken(false)); req.setCmd(PARAMS.COMMAND.getValue()); req.setBody(reqBody); // headers HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(RestClient.INSTANCE.jsonMediaType()); HttpEntity<ReqSetBody> payloadEntity = new HttpEntity<>(req, headers); RestClient.INSTANCE.handle().exchange(notifURI, HttpMethod.POST, payloadEntity, Resp.class); } catch (Exception e) { // muted } finally { BusProvider.INSTANCE.getBus().post(new Events.SingleNotifsUPDATEEvent(eventBody)); } }
private ArrayList<ContentProviderOperation> prepareBatch( Cursor cursor, Collection<CategoryItem> serverCategories) { ArrayList<ContentProviderOperation> batch = new ArrayList<>(); Map<Double, CategoryItem> map = new HashMap<Double, CategoryItem>(); for (CategoryItem item : serverCategories) { map.put(item.getId(), item); } Uri itemUri; Uri tableUri = CategoryColumns.CONTENT_URI; double canonicalId; CategoryItem dbItem; CategoryCursor itemCursor; try { while (cursor.moveToNext()) { itemCursor = new CategoryCursor(cursor); dbItem = transformer.transform(itemCursor); itemUri = Uri.withAppendedPath(tableUri, String.valueOf(itemCursor.getId())); canonicalId = itemCursor.getCategoryId(); CategoryItem webItem = map.get(canonicalId); if (webItem == null) { syncResult.stats.numDeletes++; batch.add(ContentProviderOperation.newDelete(itemUri).build()); } else { map.remove(canonicalId); if (!dbItem.equals(webItem)) { syncResult.stats.numUpdates++; batch.add( ContentProviderOperation.newUpdate(itemUri) .withValue(CategoryColumns.DESCRIPTION, webItem.getDescription()) .withValue(CategoryColumns.NAME, webItem.getName()) .build()); } } } } finally { cursor.close(); } for (CategoryItem webItem : map.values()) { syncResult.stats.numInserts++; batch.add( ContentProviderOperation.newInsert(tableUri) .withValue(CategoryColumns.DESCRIPTION, webItem.getDescription()) .withValue(CategoryColumns.NAME, webItem.getName()) .withValue(CategoryColumns.CATEGORY_ID, webItem.getId()) .build()); } return batch; }
private void removeAllTestContactsInProfile() { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ops.add( ContentProviderOperation.newDelete(RawContacts.CONTENT_URI) .withSelection(RawContacts.ACCOUNT_TYPE + "=?", new String[] {TEST_ACCOUNT_TYPE}) .build()); try { mResolver.applyBatch(ContactsContract.AUTHORITY, ops); } catch (Exception e) { // Catch all exceptions to let tearDown() run smoothly e.printStackTrace(); } }
public void buildOwnershipCleanup(List<Long> duplicateIds) { String selection = CapsuleContract.Ownerships._ID + " IN (" + CapsuleOperations.buildPreparedStatementParameters(duplicateIds.size()) + ")"; String[] selectionArgs = CapsuleOperations.convertIdsToArguments(duplicateIds); this.mOperations.add( ContentProviderOperation.newDelete(CapsuleContract.Ownerships.CONTENT_URI) .withSelection(selection, selectionArgs) .withYieldAllowed(true) .build()); }
@Override public void makeContentProviderOperations(ArrayList<ContentProviderOperation> list) { Uri uri = ScheduleContractHelper.setUriAsCalledFromSyncAdapter(ScheduleContract.Videos.CONTENT_URI); HashMap<String, String> videoHashcodes = loadVideoHashcodes(); HashSet<String> videosToKeep = new HashSet<String>(); boolean isIncrementalUpdate = videoHashcodes != null && videoHashcodes.size() > 0; if (isIncrementalUpdate) { LOGD(TAG, "Doing incremental update for videos."); } else { LOGD(TAG, "Doing FULL (non incremental) update for videos."); list.add(ContentProviderOperation.newDelete(uri).build()); } int updatedVideos = 0; for (Video video : mVideos.values()) { String hashCode = video.getImportHashcode(); videosToKeep.add(video.id); // add video, if necessary if (!isIncrementalUpdate || !videoHashcodes.containsKey(video.id) || !videoHashcodes.get(video.id).equals(hashCode)) { ++updatedVideos; boolean isNew = !isIncrementalUpdate || !videoHashcodes.containsKey(video.id); buildVideo(isNew, video, list); } } int deletedVideos = 0; if (isIncrementalUpdate) { for (String videoId : videoHashcodes.keySet()) { if (!videosToKeep.contains(videoId)) { buildDeleteOperation(videoId, list); ++deletedVideos; } } } LOGD( TAG, "Videos: " + (isIncrementalUpdate ? "INCREMENTAL" : "FULL") + " update. " + updatedVideos + " to update, " + deletedVideos + " to delete. New total: " + mVideos.size()); }
@Override public void makeContentProviderOperations(ArrayList<ContentProviderOperation> list) { Uri uri = ScheduleContractHelper.setUriAsCalledFromSyncAdapter(ScheduleContract.Speakers.CONTENT_URI); HashMap<String, String> speakerHashcodes = loadSpeakerHashcodes(); HashSet<String> speakersToKeep = new HashSet<String>(); boolean isIncrementalUpdate = speakerHashcodes != null && speakerHashcodes.size() > 0; if (isIncrementalUpdate) { LOGD(TAG, "Doing incremental update for speakers."); } else { LOGD(TAG, "Doing FULL (non incremental) update for speakers."); list.add(ContentProviderOperation.newDelete(uri).build()); } int updatedSpeakers = 0; for (Speaker speaker : mSpeakers.values()) { String hashCode = speaker.getImportHashcode(); speakersToKeep.add(speaker.id); // add speaker, if necessary if (!isIncrementalUpdate || !speakerHashcodes.containsKey(speaker.id) || !speakerHashcodes.get(speaker.id).equals(hashCode)) { ++updatedSpeakers; boolean isNew = !isIncrementalUpdate || !speakerHashcodes.containsKey(speaker.id); buildSpeaker(isNew, speaker, list); } } int deletedSpeakers = 0; if (isIncrementalUpdate) { for (String speakerId : speakerHashcodes.keySet()) { if (!speakersToKeep.contains(speakerId)) { buildDeleteOperation(speakerId, list); ++deletedSpeakers; } } } LOGD( TAG, "Speakers: " + (isIncrementalUpdate ? "INCREMENTAL" : "FULL") + " update. " + updatedSpeakers + " to update, " + deletedSpeakers + " to delete. New total: " + mSpeakers.size()); }
public void buildCapsuleDelete(Capsule capsule, boolean withYield) { // Build the Capsule URI Uri uri = ContentUris.withAppendedId(CapsuleContract.Capsules.CONTENT_URI, capsule.getId()); // Build the DELETE operation this.mOperations.add( ContentProviderOperation.newDelete(uri).withYieldAllowed(withYield).build()); // Get the capsule ID String capsuleId = String.valueOf(capsule.getId()); // Build the Discovery DELETE operation this.mOperations.add( ContentProviderOperation.newDelete(CapsuleContract.Discoveries.CONTENT_URI) .withSelection( CapsuleContract.Discoveries.CAPSULE_ID + " = ?", new String[] {capsuleId}) .withYieldAllowed(false) .build()); // Build the Ownership DELETE operation this.mOperations.add( ContentProviderOperation.newDelete(CapsuleContract.Ownerships.CONTENT_URI) .withSelection(CapsuleContract.Ownerships.CAPSULE_ID + " = ?", new String[] {capsuleId}) .withYieldAllowed(false) .build()); }
public static int removePhone(final Context context, final String phone) { ArrayList<ContentProviderOperation> ops = new ArrayList<>(); ops.add( ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI) .withSelection( ContactsContract.CommonDataKinds.Phone.NUMBER + "=?", new String[] {phone}) .build()); try { return context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops).length; } catch (RemoteException | OperationApplicationException e) { e.printStackTrace(); } return 0; }
private void testDeleteContacts(final int i) { if (mStatus[i] == SETUP) { final ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); operationList.add(ContentProviderOperation.newDelete(mAliceUri).build()); operationList.add(ContentProviderOperation.newDelete(mBobUri).build()); try { mContext.getContentResolver().applyBatch(ContactsContract.AUTHORITY, operationList); mStatus[i] = READY; } catch (RemoteException e) { Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); mStatus[i] = FAIL; } catch (OperationApplicationException e) { Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); mStatus[i] = FAIL; } // wait for deletions to move through the system delay(3000); } else if (mStatus[i] == READY) { mAliceUri = lookupContact(ALICE_PHONE); mBobUri = lookupContact(BOB_PHONE); mCharlieUri = lookupContact(CHARLIE_PHONE); mStatus[i] = PASS; if (mAliceUri != null) { mStatus[i] = FAIL; } if (mBobUri != null) { mStatus[i] = FAIL; } if (mCharlieUri != null) { mStatus[i] = FAIL; } next(); } }
private void flushLogToDB(Context context) { try { int logSize = SettingsStorage.getInstance().getProfileSwitchLogSize(); if (logSize > -1) { Builder opp = ContentProviderOperation.newDelete(DB.SwitchLogDB.CONTENT_URI); String time = Long.toString(System.currentTimeMillis() - (logSize * HOURS_IN_MILLIES)); opp.withSelection(DB.SwitchLogDB.SELECTION_BY_TIME, new String[] {time}); operations.add(opp.build()); } context.getContentResolver().applyBatch(CpuTunerProvider.AUTHORITY, operations); operations.clear(); } catch (Exception e) { Logger.w("Cannot flush to switch log"); } }
/** * Set the policy for an account atomically; this also removes any other policy associated with * the account and sets the policy key for the account. If policy is null, the policyKey is set to * 0 and the securitySyncKey to null. Also, update the account object to reflect the current * policyKey and securitySyncKey * * @param context the caller's context * @param account the account whose policy is to be set * @param policy the policy to set, or null if we're clearing the policy * @param securitySyncKey the security sync key for this account (ignored if policy is null) */ public static void setAccountPolicy( Context context, Account account, Policy policy, String securitySyncKey) { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); // Make sure this is a valid policy set if (policy != null) { policy.normalize(); // Add the new policy (no account will yet reference this) ops.add( ContentProviderOperation.newInsert(Policy.CONTENT_URI) .withValues(policy.toContentValues()) .build()); // Make the policyKey of the account our newly created policy, and set the sync key ops.add( ContentProviderOperation.newUpdate( ContentUris.withAppendedId(Account.CONTENT_URI, account.mId)) .withValueBackReference(AccountColumns.POLICY_KEY, 0) .withValue(AccountColumns.SECURITY_SYNC_KEY, securitySyncKey) .build()); } else { ops.add( ContentProviderOperation.newUpdate( ContentUris.withAppendedId(Account.CONTENT_URI, account.mId)) .withValue(AccountColumns.SECURITY_SYNC_KEY, null) .withValue(AccountColumns.POLICY_KEY, 0) .build()); } // Delete the previous policy associated with this account, if any if (account.mPolicyKey > 0) { ops.add( ContentProviderOperation.newDelete( ContentUris.withAppendedId(Policy.CONTENT_URI, account.mPolicyKey)) .build()); } try { context.getContentResolver().applyBatch(EmailContent.AUTHORITY, ops); account.refresh(context); syncAccount(context, account); } catch (RemoteException e) { // This is fatal to a remote process throw new IllegalStateException("Exception setting account policy."); } catch (OperationApplicationException e) { // Can't happen; our provider doesn't throw this exception } }
private void deleteContact(int contact_id) { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); String[] args = new String[] {contact_id + ""}; ops.add( ContentProviderOperation.newDelete(RawContacts.CONTENT_URI) .withSelection(RawContacts.CONTACT_ID + "=?", args) .build()); try { context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OperationApplicationException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void deleteAllExceptRemoteNames(Resource[] remoteResources) { String where; if (remoteResources.length != 0) { List<String> sqlFileNames = new LinkedList<String>(); for (Resource res : remoteResources) sqlFileNames.add(DatabaseUtils.sqlEscapeString(res.getName())); where = entryColumnRemoteName() + " NOT IN (" + StringUtils.join(sqlFileNames, ",") + ")"; } else where = entryColumnRemoteName() + " IS NOT NULL"; Builder builder = ContentProviderOperation.newDelete(entriesURI()) .withSelection( entryColumnParentID() + "=? AND (" + where + ")", new String[] {String.valueOf(id)}); pendingOperations.add(builder.withYieldAllowed(true).build()); }
public void test_author_bulk() throws Exception { ContentValues[] values = new ContentValues[2]; ContentValues contentValues = new ContentValues(); contentValues.put(TestContract.Author._ID, USER_NAME1); contentValues.put(TestContract.Author.FULL_NAME, FULL_NAME1); values[0] = contentValues; contentValues = new ContentValues(); contentValues.put(TestContract.Author._ID, USER_NAME2); contentValues.put(TestContract.Author.FULL_NAME, FULL_NAME2); values[1] = contentValues; getContext().getContentResolver().bulkInsert(TestContract.Author.CONTENT_URI, values); Cursor cursor = getContext() .getContentResolver() .query( TestContract.Author.CONTENT_URI, // uri null, // projection null, // selection null, // selectionArgs null // sort order ); assertTrue(cursor != null); assertTrue(cursor.getCount() == 2); ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(1); ContentProviderOperation operation = ContentProviderOperation.newDelete(TestContract.Author.CONTENT_URI).build(); operations.add(operation); getContext().getContentResolver().applyBatch(TestContract.CONTENT_AUTHORITY, operations); cursor = getContext() .getContentResolver() .query( TestContract.Author.CONTENT_URI, // uri null, // projection null, // selection null, // selectionArgs null // sort order ); assertTrue(cursor != null); assertTrue(cursor.getCount() == 0); }
/** {@inheritDoc} */ @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && ENTRY.equals(parser.getName())) { // Process single spreadsheet row at a time final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); final String speakerId = sanitizeId(entry.get(Columns.SPEAKER_TITLE), true); final Uri speakerUri = Speakers.buildSpeakerUri(speakerId); // Check for existing details, only update when changed final long localUpdated = queryItemUpdated(speakerUri, resolver); final long serverUpdated = entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found speaker " + entry.toString()); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } if (localUpdated >= serverUpdated) continue; // Clear any existing values for this speaker, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(speakerUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(Speakers.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Speakers.SPEAKER_ID, speakerId); builder.withValue(Speakers.SPEAKER_NAME, entry.get(Columns.SPEAKER_TITLE)); builder.withValue(Speakers.SPEAKER_IMAGE_URL, entry.get(Columns.SPEAKER_IMAGE_URL)); builder.withValue(Speakers.SPEAKER_COMPANY, entry.get(Columns.SPEAKER_COMPANY)); builder.withValue(Speakers.SPEAKER_ABSTRACT, entry.get(Columns.SPEAKER_ABSTRACT)); builder.withValue(Speakers.SPEAKER_URL, entry.get(Columns.SPEAKER_URL)); // Normal speaker details ready, write to provider batch.add(builder.build()); } } return batch; }
private void deleteAllSimContacts(final ContentResolver resolver) { final ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ContentProviderOperation.Builder builder = ContentProviderOperation.newDelete(RawContacts.CONTENT_URI); builder.withSelection(RawContacts.ACCOUNT_TYPE + "==?", new String[] {"sim"}); operationList.add(builder.build()); try { resolver.applyBatch(ContactsContract.AUTHORITY, operationList); } catch (RemoteException e) { Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); } catch (OperationApplicationException e) { Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); } Log.d(TAG, "delete sim task!"); }
public List<ContentProviderOperation> getRevertAllOperations(Uri entityUri) { final List<Modification> mods = getModifications(entityUri); List<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(mods.size()); for (Modification modification : mods) { if (modification.isSyncedValueSet()) { operations.add( ContentProviderOperation.newUpdate(modification.getEntityUri()) .withValue(modification.getColName(), modification.getSyncedValue()) .build()); operations.add( ContentProviderOperation.newDelete( Queries.contentUriWithId(Modifications.CONTENT_URI, modification.getId())) .build()); } } return operations; }
public static void updateContactPhoto( ContentResolver c, long rawContactId, Photo pic, boolean primary) { ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); // insert new picture try { if (pic.data != null) { // delete old picture String where = ContactsContract.Data.RAW_CONTACT_ID + " = '" + rawContactId + "' AND " + ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'"; Log.i(TAG, "Deleting picture: " + where); ContentProviderOperation.Builder builder = ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI); builder.withSelection(where, null); operationList.add(builder.build()); builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI); builder.withValue(ContactsContract.CommonDataKinds.Photo.RAW_CONTACT_ID, rawContactId); builder.withValue( ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE); builder.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, pic.data); builder.withValue(ContactsContract.Data.SYNC2, String.valueOf(pic.timestamp)); builder.withValue(ContactsContract.Data.SYNC3, pic.url); if (primary) builder.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1); operationList.add(builder.build()); } c.applyBatch(ContactsContract.AUTHORITY, operationList); } catch (Exception e) { // TODO Auto-generated catch block Log.e("ERROR:", e.toString()); } }
@Override protected void notifyDeleteByKey(Iterable<Long> keys) { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); for (Long key : keys) { if (key != null) { ops.add( ContentProviderOperation.newDelete(ContentUris.withAppendedId(CONTENT_URI, key)) .build()); } } try { if (contextWeakReference.get() != null) contextWeakReference.get().getContentResolver().applyBatch(AUTHORITY, ops); } catch (RemoteException e) { e.printStackTrace(); } catch (OperationApplicationException e) { e.printStackTrace(); } }
/** * When the delete checked label icon in the toolbar is checked this method is called to removed * the checked items. * * @param context Parent Activity used to get a Content Resolver. */ public void deleteItems(Context context) { ArrayList<ContentProviderOperation> operations = new ArrayList<>(); ContentProviderOperation operation; Set<Long> deleteSet = mAdapter.getSelectedRows(); for (long id : deleteSet) { String[] selectionArgs = new String[] {String.valueOf(id)}; operation = ContentProviderOperation.newDelete(MSLContentProvider.CONTENT_URI) .withSelection(MSLTable.COLUMN_ID + " = ?", selectionArgs) .build(); operations.add(operation); } try { context.getContentResolver().applyBatch(MSLContentProvider.AUTHORITY, operations); } catch (RemoteException | OperationApplicationException ignored) { } mAdapter.setSelectedRows(new LinkedHashSet<Long>()); }
private void deleteContact(String name) { ContentResolver cr = getContentResolver(); String where = ContactsContract.Data.DISPLAY_NAME + " = ? "; String[] params = new String[] {name}; ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ops.add( ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI) .withSelection(where, params) .build()); try { cr.applyBatch(ContactsContract.AUTHORITY, ops); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OperationApplicationException e) { // TODO Auto-generated catch block e.printStackTrace(); } Toast.makeText(this, "Deleted the contact with name '" + name + "'", Toast.LENGTH_SHORT).show(); }
/** Write all known email addresses of a key (derived from user ids) to a given raw contact */ private static void writeContactEmail( ArrayList<ContentProviderOperation> ops, ContentResolver resolver, long rawContactId, long masterKeyId) { ops.add( selectByRawContactAndItemType( ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI), rawContactId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE) .build()); Cursor ids = resolver.query( UserPackets.buildUserIdsUri(masterKeyId), new String[] {UserPackets.USER_ID}, UserPackets.IS_REVOKED + "=0", null, null); if (ids != null) { while (ids.moveToNext()) { KeyRing.UserId userId = KeyRing.splitUserId(ids.getString(0)); if (userId.email != null) { ops.add( referenceRawContact( ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI), rawContactId) .withValue( ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Email.DATA, userId.email) .build()); } } ids.close(); } }
public void commitImpl(int maxOpsPerBatch) throws RemoteException, OperationApplicationException { // Use a batch operation to handle the changes ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); // Maximum size of message text per fetch int numFetched = fetchedEmails.size(); LogUtils.d( TAG, "commitImpl: maxOpsPerBatch=%d numFetched=%d numNew=%d " + "numDeleted=%d numChanged=%d", maxOpsPerBatch, numFetched, newEmails.size(), deletedEmails.size(), changedEmails.size()); for (EmailContent.Message msg : fetchedEmails) { // Find the original message's id (by serverId and mailbox) Cursor c = getServerIdCursor(msg.mServerId, EmailContent.ID_PROJECTION); String id = null; try { if (c.moveToFirst()) { id = c.getString(EmailContent.ID_PROJECTION_COLUMN); while (c.moveToNext()) { // This shouldn't happen, but clean up if it does Long dupId = Long.parseLong(c.getString(EmailContent.ID_PROJECTION_COLUMN)); userLog("Delete duplicate with id: " + dupId); deletedEmails.add(dupId); } } } finally { c.close(); } // If we find one, we do two things atomically: 1) set the body text for the // message, and 2) mark the message loaded (i.e. completely loaded) if (id != null) { LogUtils.i(TAG, "Fetched body successfully for %s", id); final String[] bindArgument = new String[] {id}; ops.add( ContentProviderOperation.newUpdate(EmailContent.Body.CONTENT_URI) .withSelection(EmailContent.Body.SELECTION_BY_MESSAGE_KEY, bindArgument) .withValue(EmailContent.BodyColumns.TEXT_CONTENT, msg.mText) .build()); ops.add( ContentProviderOperation.newUpdate(EmailContent.Message.CONTENT_URI) .withSelection(MessageColumns._ID + "=?", bindArgument) .withValue(MessageColumns.FLAG_LOADED, EmailContent.Message.FLAG_LOADED_COMPLETE) .build()); } applyBatchIfNeeded(ops, maxOpsPerBatch, false); } /** M: "Bad Sync Key" recovery process @{ */ if (mMailbox.mId == Exchange.sBadSyncKeyMailboxId && newEmails.size() > 0) { LogUtils.i(Eas.BSK_TAG, "newEmails count:" + newEmails.size()); // Delete the local mails older than the oldest mail timestamp in the 1st window ExchangePreferences pref = ExchangePreferences.getPreferences(mContext); boolean isStaleMailsRemoved = pref.getRemovedStaleMails(); if (!isStaleMailsRemoved) { // Get the oldest mail's time stamp long oldestTimestamp = 0; oldestTimestamp = newEmails.get(0).mTimeStamp; for (Message msg : newEmails) { if (msg.mTimeStamp < oldestTimestamp) { oldestTimestamp = msg.mTimeStamp; } } LogUtils.i(Eas.BSK_TAG, "Oldest timestamp: " + oldestTimestamp); // Delete all the local mails older than the time stamp int rowDeleted = mContentResolver.delete( Message.CONTENT_URI, WHERE_MESSAGE_TIMESTAMP_LESS_THAN, new String[] {String.valueOf(oldestTimestamp), String.valueOf(mMailbox.mId)}); LogUtils.i(Eas.BSK_TAG, rowDeleted + " local stale mails were deleted"); // Set all mails of this mailbox as "dirty" at first. Then matching local mail // with the new mail by their timestamp. If found, clear the "dirty" flag. In // this way, we can ultimately mark the stale local mails and remove them ContentValues cv = new ContentValues(); cv.put(MessageColumns.DIRTY, "1"); mContentResolver.update( Message.CONTENT_URI, cv, WHERE_MAILBOX_KEY, new String[] {String.valueOf(mMailbox.mId)}); pref.setRemovedStaleMails(true); } // Remove the stale flag of the local mails which can be found in the new-synchronized mails // (by compare their time-stamp). Note that server id can not regarded as the identity of // a mail because it might be changed by server in the process of the full re-sync LogUtils.i(Eas.BSK_TAG, "Finding all the local mails with the same timestamp"); StringBuilder timestampList = new StringBuilder("("); for (Message msg : newEmails) { timestampList.append(msg.mTimeStamp); timestampList.append(','); } // Delete the last comma if (!newEmails.isEmpty()) { timestampList.deleteCharAt(timestampList.length() - 1); } timestampList.append(")"); String selection = MessageColumns.MAILBOX_KEY + "=" + Long.toString(mMailbox.mId) + " AND " + MessageColumns.TIMESTAMP + " IN " + timestampList.toString(); LogUtils.i(Eas.BSK_TAG, "selection clause: " + selection); Cursor c = mContentResolver.query( Message.CONTENT_URI, new String[] {MessageColumns._ID, MessageColumns.TIMESTAMP}, selection, null, null); try { if (c != null) { final int columnMessageId = 0; final int columnTimestamp = 1; ArrayList<ContentProviderOperation> bskOps = new ArrayList<ContentProviderOperation>(); LogUtils.i( Eas.BSK_TAG, "For current window, found " + c.getCount() + " mails existed in local DB"); while (c.moveToNext()) { long timestamp = c.getLong(columnTimestamp); for (Message msg : newEmails) { if (msg.mTimeStamp == timestamp) { // Update the properties of local mails ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, msg.mServerId); cv.put(MessageColumns.FLAG_FAVORITE, msg.mFlagFavorite); cv.put(MessageColumns.FLAGS, msg.mFlags); cv.put(MessageColumns.FLAG_READ, msg.mFlagRead); cv.put(MessageColumns.DIRTY, "0"); bskOps.add( ContentProviderOperation.newUpdate( ContentUris.withAppendedId( Message.CONTENT_URI, c.getInt(columnMessageId))) .withValues(cv) .build()); // Remove the existed mail from new mail list, then it would not be store again newEmails.remove(msg); applyBatchIfNeeded(bskOps, maxOpsPerBatch, false); break; } } } applyBatchIfNeeded(bskOps, maxOpsPerBatch, true); } } catch (RemoteException e) { // There is nothing to be done here; fail by returning null LogUtils.i(Eas.BSK_TAG, "RemoteException when applyBatch"); } catch (OperationApplicationException e) { // There is nothing to be done here; fail by returning null LogUtils.i(Eas.BSK_TAG, "OperationApplicationException when applyBatch"); } finally { if (c != null) { c.close(); } } LogUtils.i( Eas.BSK_TAG, "There are " + newEmails.size() + " mail(s) remaining in the newEmails list"); } /** @} */ /// M: For smart push, record new mails' coming DataCollectUtils.recordNewMails(mContext, newEmails); for (EmailContent.Message msg : newEmails) { msg.addSaveOps(ops); applyBatchIfNeeded(ops, maxOpsPerBatch, false); } /// M: Log receive new message. @{ EmailContent.Message.logMessageReceived(mContext, newEmails.toArray(new Message[] {})); /// @} for (Long id : deletedEmails) { /** * M: 1. The attachments were belonged to the com.android.email application, delete * attachments here, it would fail, so mask the function call to * AttachmentUtilities.deleteAllAttachmentFiles here and do the attachment delete operation on * Email provider. 2. Add a new parameter (account id) to URI for delete attachments on Email * side. @{ */ Uri.Builder builder = EmailContent.Message.CONTENT_URI.buildUpon(); builder.appendEncodedPath(String.valueOf(id)); builder.appendQueryParameter( AttachmentUtilities.KEY_ACCOUNT_ID, String.valueOf(mAccount.mId)); ops.add(ContentProviderOperation.newDelete(builder.build()).build()); // AttachmentUtilities.deleteAllAttachmentFiles(mContext, mAccount.mId, id); /** @} */ applyBatchIfNeeded(ops, maxOpsPerBatch, false); } if (!changedEmails.isEmpty()) { // Server wins in a conflict... for (ServerChange change : changedEmails) { ContentValues cv = new ContentValues(); if (change.read != null) { cv.put(EmailContent.MessageColumns.FLAG_READ, change.read); } if (change.flag != null) { cv.put(EmailContent.MessageColumns.FLAG_FAVORITE, change.flag); } if (change.flags != null) { cv.put(EmailContent.MessageColumns.FLAGS, change.flags); } ops.add( ContentProviderOperation.newUpdate( ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, change.id)) .withValues(cv) .build()); } applyBatchIfNeeded(ops, maxOpsPerBatch, false); } // We only want to update the sync key here ContentValues mailboxValues = new ContentValues(); mailboxValues.put(Mailbox.SYNC_KEY, mMailbox.mSyncKey); ops.add( ContentProviderOperation.newUpdate( ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailbox.mId)) .withValues(mailboxValues) .build()); applyBatchIfNeeded(ops, maxOpsPerBatch, true); userLog(mMailbox.mDisplayName, " SyncKey saved as: ", mMailbox.mSyncKey); }