List of usage examples for android.content ContentProviderClient applyBatch
public @NonNull ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations) throws RemoteException, OperationApplicationException
From source file:dev.drsoran.moloko.sync.SyncAdapter.java
private void applyLocalOperations(ContentProviderClient provider) { final ArrayList<ContentProviderOperation> contentProviderOperationsBatch = new ArrayList<ContentProviderOperation>(); for (IContentProviderSyncOperation contentProviderSyncOperation : molokoSyncResult.localOps) { final int count = contentProviderSyncOperation.getBatch(contentProviderOperationsBatch); ContentProviderSyncOperation.updateSyncResult(syncResult, contentProviderSyncOperation.getOperationType(), count); }/*from w w w . j a v a 2 s. c o m*/ try { provider.applyBatch(contentProviderOperationsBatch); } catch (RemoteException e) { ++syncResult.stats.numIoExceptions; throw new SyncException(e); } catch (OperationApplicationException e) { syncResult.databaseError = true; throw new SyncException(e); } }
From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java
private long updateSyncRecord(ContentProviderClient provider) throws RemoteException, OperationApplicationException { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ContentProviderOperation op = ContentProviderOperation.newInsert(GMSSyncs.CONTENT_URI) .withValue(GMSSync.SYNC_DATE, System.currentTimeMillis()).build(); ops.add(op);/*from w w w.j a v a2 s . c o m*/ ContentProviderResult[] results = provider.applyBatch(ops); return (results[0].uri != null) ? ContentUris.parseId(results[0].uri) : -1L; }
From source file:com.google.android.apps.gutenberg.provider.SyncAdapter.java
private void syncEvents(ContentProviderClient provider, String cookie) { try {/*from w w w . j a v a2s . c o m*/ RequestQueue requestQueue = GutenbergApplication.from(getContext()).getRequestQueue(); JSONArray events = getEvents(requestQueue, cookie); Pair<String[], ContentValues[]> pair = parseEvents(events); String[] eventIds = pair.first; provider.bulkInsert(Table.EVENT.getBaseUri(), pair.second); ArrayList<ContentProviderOperation> operations = new ArrayList<>(); operations.add(ContentProviderOperation.newDelete(Table.EVENT.getBaseUri()) .withSelection(Table.Event.ID + " NOT IN ('" + TextUtils.join("', '", eventIds) + "')", null) .build()); operations.add(ContentProviderOperation.newDelete(Table.ATTENDEE.getBaseUri()) .withSelection(Table.Attendee.EVENT_ID + " NOT IN ('" + TextUtils.join("', '", eventIds) + "')", null) .build()); provider.applyBatch(operations); for (String eventId : eventIds) { JSONArray attendees = getAttendees(requestQueue, eventId, cookie); provider.bulkInsert(Table.ATTENDEE.getBaseUri(), parseAttendees(eventId, attendees)); } Log.d(TAG, eventIds.length + " event(s) synced."); } catch (ExecutionException | InterruptedException | JSONException | RemoteException | OperationApplicationException e) { Log.e(TAG, "Error performing sync.", e); } }
From source file:org.totschnig.myexpenses.sync.SyncAdapter.java
private void writeRemoteChangesToDbPart(ContentProviderClient provider, List<TransactionChange> remoteChanges, long accountId) throws RemoteException, OperationApplicationException { ArrayList<ContentProviderOperation> ops = new ArrayList<>(); ops.add(ContentProviderOperation/* w w w . j a va 2 s .c om*/ .newInsert(TransactionProvider.DUAL_URI.buildUpon() .appendQueryParameter(TransactionProvider.QUERY_PARAMETER_SYNC_BEGIN, "1").build()) .build()); Stream.of(remoteChanges).filter(change -> !(change.isCreate() && uuidExists(change.uuid()))) .forEach(change -> collectOperations(change, accountId, ops, -1)); ops.add(ContentProviderOperation.newDelete(TransactionProvider.DUAL_URI.buildUpon() .appendQueryParameter(TransactionProvider.QUERY_PARAMETER_SYNC_END, "1").build()).build()); ContentProviderResult[] contentProviderResults = provider.applyBatch(ops); int opsSize = ops.size(); int resultsSize = contentProviderResults.length; if (opsSize != resultsSize) { AcraHelper.report( String.format(Locale.ROOT, "applied %d operations, received %d results", opsSize, resultsSize)); } }
From source file:com.rukman.emde.smsgroups.platform.GMSContactOperations.java
public static long addGroupToContacts(Context context, ContentProviderClient provider, Account account, JSONObject group, SyncResult result) throws RemoteException, OperationApplicationException, JSONException { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ContentProviderOperation.Builder op = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI) .withValue(RawContacts.ACCOUNT_TYPE, GMSApplication.ACCOUNT_TYPE) .withValue(RawContacts.ACCOUNT_NAME, account.name) .withValue(RawContacts.SOURCE_ID, group.getString(JSONKeys.KEY_ID)); ops.add(op.build());/*from w w w . j a va2s . c o m*/ op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0) .withValue(Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) .withValue(CommonDataKinds.StructuredName.DISPLAY_NAME, group.getString(JSONKeys.KEY_NAME)); ops.add(op.build()); op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0) .withValue(Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE) .withValue(CommonDataKinds.Phone.NUMBER, group.get(JSONKeys.KEY_PHONE)) .withValue(CommonDataKinds.Phone.TYPE, CommonDataKinds.Phone.TYPE_MAIN); ops.add(op.build()); op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0) .withValue(Data.MIMETYPE, CommonDataKinds.Photo.CONTENT_ITEM_TYPE).withYieldAllowed(true); ops.add(op.build()); InputStream is = null; ByteArrayOutputStream baos = null; try { is = context.getAssets().open("gms.png", AssetManager.ACCESS_BUFFER); baos = new ByteArrayOutputStream(); int value = is.read(); while (value != -1) { baos.write(value); value = is.read(); } op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) .withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Photo.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, baos.toByteArray()) .withYieldAllowed(true); ops.add(op.build()); } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } if (baos != null) { baos.close(); } } catch (IOException ignore) { } } ContentProviderResult[] results = provider.applyBatch(ops); return (results[0].uri != null) ? ContentUris.parseId(results[0].uri) : -1L; }
From source file:org.voidsink.anewjkuapp.calendar.CalendarUtils.java
private static boolean deleteKusssEvents(Context context, String calId) { if (calId != null) { ContentProviderClient provider = context.getContentResolver() .acquireContentProviderClient(CalendarContractWrapper.Events.CONTENT_URI()); if (provider == null) { return false; }//from w w w.j ava2s .c o m try { Uri calUri = CalendarContractWrapper.Events.CONTENT_URI(); Cursor c = loadEvent(provider, calUri, calId); if (c != null) { try { ArrayList<ContentProviderOperation> batch = new ArrayList<>(); long deleteFrom = new Date().getTime() - DateUtils.DAY_IN_MILLIS; while (c.moveToNext()) { long eventDTStart = c.getLong(CalendarUtils.COLUMN_EVENT_DTSTART); if (eventDTStart > deleteFrom) { String eventId = c.getString(COLUMN_EVENT_ID); // Log.d(TAG, "---------"); String eventKusssId = null; // get kusssId from extended properties Cursor c2 = provider.query(CalendarContract.ExtendedProperties.CONTENT_URI, CalendarUtils.EXTENDED_PROPERTIES_PROJECTION, CalendarContract.ExtendedProperties.EVENT_ID + " = ?", new String[] { eventId }, null); if (c2 != null) { while (c2.moveToNext()) { if (c2.getString(1).contains(EXTENDED_PROPERTY_NAME_KUSSS_ID)) { eventKusssId = c2.getString(2); } } c2.close(); } if (TextUtils.isEmpty(eventKusssId)) { eventKusssId = c.getString(COLUMN_EVENT_KUSSS_ID_LEGACY); } if (!TextUtils.isEmpty(eventKusssId)) { if (eventKusssId.startsWith("at-jku-kusss-exam-") || eventKusssId.startsWith("at-jku-kusss-coursedate-")) { Uri deleteUri = calUri.buildUpon().appendPath(eventId).build(); Log.d(TAG, "Scheduling delete: " + deleteUri); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); } } } } if (batch.size() > 0) { Log.d(TAG, "Applying batch update"); provider.applyBatch(batch); Log.d(TAG, "Notify resolver"); } else { Log.w(TAG, "No batch operations found! Do nothing"); } } catch (RemoteException | OperationApplicationException e) { Analytics.sendException(context, e, true); return false; } } } finally { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { provider.close(); } else { provider.release(); } } return false; } return true; }
From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java
private ContentProviderResult[] optimisticallyCreateGroupAndContacts(JSONObject group, ContentProviderClient provider, ContentProviderClient contactsProvider, String authToken, Account account, SyncResult syncResult) throws JSONException, RemoteException, OperationApplicationException { String groupCloudId = group.getString(JSONKeys.KEY_ID); ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); // If the first operation asserts, that means the group already exists // Operation 0 ContentProviderOperation.Builder op = ContentProviderOperation.newAssertQuery(GMSGroups.CONTENT_URI) .withValue(GMSGroup._ID, "").withValue(GMSGroup.CLOUD_ID, "") .withSelection(GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }).withExpectedCount(0); ops.add(op.build());//from ww w. j av a 2 s. c o m // If we get this far, create the group from the information the JSON object // Operation 1 ContentValues groupValues = GMSApplication.getGroupValues(group); op = ContentProviderOperation.newInsert(GMSGroups.CONTENT_URI).withValues(groupValues) .withValue(GMSGroup.STATUS, GMSGroup.STATUS_SYNCED); ops.add(op.build()); // And add the contacts // Operations 2 - N + 2 where N is the number of members in group if (group.has(JSONKeys.KEY_MEMBERS)) { JSONArray membersArray = group.getJSONArray(JSONKeys.KEY_MEMBERS); int numMembers = membersArray.length(); for (int j = 0; j < numMembers; ++j) { JSONObject member = membersArray.getJSONObject(j); ContentValues memberValues = GMSApplication.getMemberValues(member); op = ContentProviderOperation.newInsert(GMSContacts.CONTENT_URI).withValues(memberValues) .withValueBackReference(GMSContact.GROUP_ID, 1) .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED); ops.add(op.build()); } } ContentProviderResult[] results = provider.applyBatch(ops); // Create the contact on the device Uri groupUri = results[1].uri; if (groupUri != null) { Cursor cursor = null; try { cursor = GMSContactOperations.findGroupInContacts(contactsProvider, account, groupCloudId); if (cursor.getCount() > 0) { Assert.assertTrue(cursor.moveToFirst()); long oldContactId = cursor.getLong(0); GMSContactOperations.removeGroupFromContacts(contactsProvider, account, oldContactId, syncResult); } long contactId = GMSContactOperations.addGroupToContacts(getContext(), contactsProvider, account, group, syncResult); if (contactId > 0) { ContentValues values = new ContentValues(); values.put(GMSGroup.RAW_CONTACT_ID, contactId); provider.update(groupUri, values, null, null); addNewGroupNotification(group); } } finally { if (cursor != null) { cursor.close(); } } } return results; }
From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java
private ContentProviderResult[] optimisticallyUpdateGroup(JSONObject group, ContentProviderClient provider, ContentProviderClient contactsProvider, String authToken, Account account, SyncResult syncResult) throws JSONException, RemoteException { String groupCloudId = null;/*from w w w .j a v a 2 s. c om*/ String version = null; try { groupCloudId = group.getString(JSONKeys.KEY_ID); version = group.getString(JSONKeys.KEY_VERSION); ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); // Operation 0 - we believe the record exists, but we'll check, inside a transaction, to make sure ContentProviderOperation op; op = ContentProviderOperation.newAssertQuery(GMSGroups.CONTENT_URI) .withSelection(GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }).withExpectedCount(1) .build(); ops.add(op); // Operation 1 - we know it exists. If its the right version, we don't need to do the update // So we assert that we'll find zero records with the current version and if that's right, we'll update our // record, including the version with the new record data op = ContentProviderOperation.newAssertQuery(GMSGroups.CONTENT_URI) .withSelection(GMSGroup.CLOUD_ID + "=? AND " + GMSGroup.VERSION + "=?", new String[] { groupCloudId, version }) .withExpectedCount(0).build(); ops.add(op); // If we get this far, update the existing group from the information in the JSON object // Operation 2 ContentValues groupValues = GMSApplication.getGroupValues(group); op = ContentProviderOperation.newUpdate(GMSGroups.CONTENT_URI) .withSelection(GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }).withValues(groupValues) .withValue(GMSGroup.STATUS, GMSGroup.STATUS_SYNCED).withExpectedCount(1).build(); ops.add(op); return provider.applyBatch(ops); } catch (OperationApplicationException e) { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ContentProviderOperation op; // Operation 0 - we know it exists. If its the right version, we don't need to do the update // So we assert that we'll find zero records with the current version and if that's right, we'll update our // record, including the version with the new record data op = ContentProviderOperation.newAssertQuery(GMSGroups.CONTENT_URI) .withSelection(GMSGroup.CLOUD_ID + "=? AND " + GMSGroup.VERSION + "=?", new String[] { groupCloudId, version }) .withExpectedCount(1).build(); ops.add(op); // If we get this far we only need to update the is_synced field in the database // Operation 1 op = ContentProviderOperation.newUpdate(GMSGroups.CONTENT_URI) .withSelection(GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }) .withValue(GMSGroup.STATUS, GMSGroup.STATUS_SYNCED).withExpectedCount(1).build(); ops.add(op); try { return provider.applyBatch(ops); } catch (OperationApplicationException e1) { e1.printStackTrace(); syncResult.stats.numSkippedEntries++; } } return null; }
From source file:com.example.jumpnote.android.SyncAdapter.java
public void reconcileSyncedNotes(ContentProviderClient provider, Account account, List<ModelJava.Note> changedNotes, SyncStats syncStats) throws RemoteException, OperationApplicationException { Cursor noteCursor;/*from w w w . ja v a 2 s . co m*/ ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(); for (ModelJava.Note changedNote : changedNotes) { Uri noteUri = null; if (changedNote.getId() != null) { noteUri = addCallerIsSyncAdapterParameter( JumpNoteContract.buildNoteUri(account.name, Long.parseLong(changedNote.getId()))); } else { noteCursor = provider.query(JumpNoteContract.buildNoteListUri(account.name), PROJECTION, JumpNoteContract.Notes.SERVER_ID + " = ?", new String[] { changedNote.getServerId() }, null); if (noteCursor.moveToNext()) { noteUri = addCallerIsSyncAdapterParameter( JumpNoteContract.buildNoteUri(account.name, noteCursor.getLong(0))); } noteCursor.close(); } if (changedNote.isPendingDelete()) { // Handle server-side delete. if (noteUri != null) { operations.add(ContentProviderOperation.newDelete(noteUri).build()); syncStats.numDeletes++; } } else { ContentValues values = changedNote.toContentValues(); if (noteUri != null) { // Handle server-side update. operations.add(ContentProviderOperation.newUpdate(noteUri).withValues(values).build()); syncStats.numUpdates++; } else { // Handle server-side insert. operations .add(ContentProviderOperation .newInsert(addCallerIsSyncAdapterParameter( JumpNoteContract.buildNoteListUri(account.name))) .withValues(values).build()); syncStats.numInserts++; } } } provider.applyBatch(operations); }
From source file:com.samsung.android.remindme.SyncAdapter.java
public void reconcileSyncedAlerts(ContentProviderClient provider, Account account, List<ModelJava.Alert> changedAlerts, SyncStats syncStats) throws RemoteException, OperationApplicationException { Cursor alertCursor;/* w w w.j av a 2 s. c o m*/ ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(); for (ModelJava.Alert changedAlert : changedAlerts) { Uri alertUri = null; if (changedAlert.getId() != null) { alertUri = addCallerIsSyncAdapterParameter( RemindMeContract.buildAlertUri(account.name, Long.parseLong(changedAlert.getId()))); } else { alertCursor = provider.query(RemindMeContract.buildAlertListUri(account.name), PROJECTION, RemindMeContract.Alerts.SERVER_ID + " = ?", new String[] { changedAlert.getServerId() }, null); if (alertCursor.moveToNext()) { alertUri = addCallerIsSyncAdapterParameter( RemindMeContract.buildAlertUri(account.name, alertCursor.getLong(0))); } alertCursor.close(); } if (changedAlert.isPendingDelete()) { // Handle server-side delete. if (alertUri != null) { operations.add(ContentProviderOperation.newDelete(alertUri).build()); syncStats.numDeletes++; } } else { ContentValues values = changedAlert.toContentValues(); if (alertUri != null) { // Handle server-side update. operations.add(ContentProviderOperation.newUpdate(alertUri).withValues(values).build()); syncStats.numUpdates++; } else { // Handle server-side insert. operations .add(ContentProviderOperation .newInsert(addCallerIsSyncAdapterParameter( RemindMeContract.buildAlertListUri(account.name))) .withValues(values).build()); syncStats.numInserts++; } } } provider.applyBatch(operations); }