android.content.OperationApplicationException Java Examples

The following examples show how to use android.content.OperationApplicationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TaskProviderObserverTest.java    From opentasks with Apache License 2.0 6 votes vote down vote up
/**
 * Test that an update that doesn't change anything doesn't trigger a notification.
 */
@Test
public void testNoOpUpdate() throws RemoteException, OperationApplicationException
{
    RowSnapshot<TaskLists> taskList = new VirtualRowSnapshot<>(new LocalTaskListsTable(mAuthority));
    RowSnapshot<Tasks> task = new VirtualRowSnapshot<>(new TaskListScoped(taskList, new TasksTable(mAuthority)));
    OperationsQueue queue = new BasicOperationsQueue(mClient);

    queue.enqueue(
            new Seq<>(
                    new Put<>(taskList, new NameData("list1")),
                    new Put<>(task, new TitleData("task1"))));
    queue.flush();

    assertThat(new Seq<>(
                    new Put<>(task, new TitleData("task1"))),
            notifies(
                    TaskContract.getContentUri(mAuthority),
                    queue,
                    // there should no notification
                    emptyIterable()));
}
 
Example #2
Source File: DisplayActivity.java    From coursera-android with MIT License 6 votes vote down vote up
private void insertAllNewContacts() {

        // Set up a batch operation on Contacts ContentProvider
        ArrayList<ContentProviderOperation> batchOperation = new ArrayList<>();

        for (String name : mNames) {
            addRecordToBatchInsertOperation(name, batchOperation);
        }

        try {

            // Apply all batched operations
            getContentResolver().applyBatch(ContactsContract.AUTHORITY,
                    batchOperation);

        } catch (RemoteException | OperationApplicationException e) {
            Log.i(TAG, "RemoteException");
        }

    }
 
Example #3
Source File: ItemsProvider.java    From make-your-app-material with Apache License 2.0 6 votes vote down vote up
/**
 * Apply the given set of {@link ContentProviderOperation}, executing inside
 * a {@link SQLiteDatabase} transaction. All changes will be rolled back if
 * any single one fails.
 */
@NonNull
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations)
        throws OperationApplicationException {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        final int numOperations = operations.size();
        final ContentProviderResult[] results = new ContentProviderResult[numOperations];
        for (int i = 0; i < numOperations; i++) {
            results[i] = operations.get(i).apply(this, results, i);
        }
        db.setTransactionSuccessful();
        return results;
    } finally {
        db.endTransaction();
    }
}
 
Example #4
Source File: DevicesProvider.java    From device-database with Apache License 2.0 6 votes vote down vote up
@Override
public @NonNull ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
    final SQLiteDatabase db = helper.getWritableDatabase();

    db.beginTransaction();

    try {
        final ContentProviderResult[] results =
                super.applyBatch(operations);
        db.setTransactionSuccessful();

        return results;
    } finally {
        db.endTransaction();
    }
}
 
Example #5
Source File: EspContactTool.java    From espresso-macchiato with MIT License 6 votes vote down vote up
public static Uri add(ContactSpec spec) {

        // original code http://stackoverflow.com/questions/4744187/how-to-add-new-contacts-in-android
        // good blog http://androiddevelopement.blogspot.de/2011/07/insert-update-delete-view-contacts-in.html

        ArrayList<ContentProviderOperation> ops = new ArrayList<>();

        addContactBase(ops);
        addContactDisplayName(spec, ops);
        addContactAddress(spec, ops);

        try {
            ContentProviderResult[] results = InstrumentationRegistry.getTargetContext().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            return results[0].uri;
        } catch (RemoteException | OperationApplicationException e) {
            throw new IllegalStateException("Could not add contact", e);
        }
    }
 
Example #6
Source File: BatchOperation.java    From tindroid with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("UnusedReturnValue")
List<Uri> execute() {
    List<Uri> resultUris = new ArrayList<>();
    if (mOperations.size() == 0) {
        return resultUris;
    }
    // Apply the mOperations to the content provider
    try {
        ContentProviderResult[] results = mResolver.applyBatch(ContactsContract.AUTHORITY, mOperations);
        if (results.length > 0) {
            for (ContentProviderResult result : results) {
                resultUris.add(result.uri);
            }
        }
    } catch (final OperationApplicationException | RemoteException e) {
        Log.e(TAG, "storing contact data failed", e);
    }
    mOperations.clear();
    return resultUris;
}
 
Example #7
Source File: FileContentProvider.java    From Cirrus_depricated with GNU General Public License v2.0 6 votes vote down vote up
@Override
public ContentProviderResult[] applyBatch (ArrayList<ContentProviderOperation> operations)
        throws OperationApplicationException {
    Log_OC.d("FileContentProvider", "applying batch in provider " + this +
            " (temporary: " + isTemporary() + ")" );
    ContentProviderResult[] results = new ContentProviderResult[operations.size()];
    int i=0;

    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    db.beginTransaction();  // it's supposed that transactions can be nested
    try {
        for (ContentProviderOperation operation : operations) {
            results[i] = operation.apply(this, results, i);
            i++;
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
    Log_OC.d("FileContentProvider", "applied batch in provider " + this);
    return results;
}
 
Example #8
Source File: RepoPersister.java    From fdroidclient with GNU General Public License v3.0 6 votes vote down vote up
private void flushApksToDbInBatch(Map<String, Long> appIds) throws IndexUpdater.UpdateException {
    List<Apk> apksToSaveList = new ArrayList<>();
    for (Map.Entry<String, List<Apk>> entries : apksToSave.entrySet()) {
        for (Apk apk : entries.getValue()) {
            apk.appId = appIds.get(apk.packageName);
        }
        apksToSaveList.addAll(entries.getValue());
    }

    calcApkCompatibilityFlags(apksToSaveList);

    ArrayList<ContentProviderOperation> apkOperations = insertApks(apksToSaveList);

    try {
        context.getContentResolver().applyBatch(TempApkProvider.getAuthority(), apkOperations);
    } catch (RemoteException | OperationApplicationException e) {
        throw new IndexUpdater.UpdateException("An internal error occurred while updating the database", e);
    }
}
 
Example #9
Source File: PersistNotificationAction.java    From opentasks with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Context context, ContentProviderClient contentProviderClient, RowDataSnapshot<TaskContract.Instances> data, Uri taskUri) throws RemoteException, OperationApplicationException
{
    try
    {
        RowStateInfo rsi = new RowStateInfo(data);
        new NotificationPrefs(context).next()
                .edit()
                .putString(
                        taskUri.toString(),
                        new JSONObject()
                                .put("version", new TaskVersion(data).value())
                                .put("started", rsi.started())
                                .put("due", rsi.due())
                                .put("done", rsi.done())
                                .put("ongoing", rsi.pinned()).toString())
                .apply();
    }
    catch (JSONException e)
    {
        throw new RuntimeException("Unable to serialize to JSON", e);
    }
}
 
Example #10
Source File: DataProvider.java    From narrate-android with Apache License 2.0 6 votes vote down vote up
/**
 * Apply the given set of {@link ContentProviderOperation}, executing inside
 * a {@link SQLiteDatabase} transaction. All changes will be rolled back if
 * any single one fails.
 */
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
        throws OperationApplicationException {
    final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        final int numOperations = operations.size();
        final ContentProviderResult[] results = new ContentProviderResult[numOperations];
        for (int i = 0; i < numOperations; i++) {
            results[i] = operations.get(i).apply(this, results, i);
        }
        db.setTransactionSuccessful();
        return results;
    } finally {
        db.endTransaction();
    }
}
 
Example #11
Source File: V2exProvider.java    From v2ex with Apache License 2.0 6 votes vote down vote up
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        final int numOperations = operations.size();
        final ContentProviderResult[] results = new ContentProviderResult[numOperations];
        for (int i = 0; i < numOperations; i++) {
            results[i] = operations.get(i).apply(this, results, i);
        }
        db.setTransactionSuccessful();
        return results;
    } finally {
        db.endTransaction();
    }
}
 
Example #12
Source File: EventLoader.java    From RememBirthday with GNU General Public License v3.0 6 votes vote down vote up
public synchronized static void updateEvent(Context context, Contact contact, DateUnknownYear newBirthday) throws EventException {
    // TODO UNIFORMISE
    for (CalendarEvent event : getEventsSavedOrCreateNewsForEachYear(context, contact)) {
        // Construct each anniversary of new birthday
        int year = new DateTime(event.getDate()).getYear();
        Date newBirthdayDate = DateUnknownYear.getDateWithYear(newBirthday.getDate(), year);
        event.setDateStart(newBirthdayDate);
        event.setAllDay(true);
        ArrayList<ContentProviderOperation> operations = new ArrayList<>();
        ContentProviderOperation contentProviderOperation = EventProvider.update(event);
        operations.add(contentProviderOperation);
        try {
            ContentProviderResult[] contentProviderResults =
                    context.getContentResolver().applyBatch(CalendarContract.AUTHORITY, operations);
            for(ContentProviderResult contentProviderResult : contentProviderResults) {
                if (contentProviderResult.count != 0)
                    Log.d(TAG, "Update event : " + event.toString());
            }
        } catch (RemoteException|OperationApplicationException e) {
            Log.e(TAG, "Unable to update event : " + e.getMessage());
        }
    }
}
 
Example #13
Source File: RemoteContentProvider.java    From VirtualAPK with Apache License 2.0 6 votes vote down vote up
@NonNull
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
    try {
        Field uriField = ContentProviderOperation.class.getDeclaredField("mUri");
        uriField.setAccessible(true);
        for (ContentProviderOperation operation : operations) {
            Uri pluginUri = Uri.parse(operation.getUri().getQueryParameter(KEY_URI));
            uriField.set(operation, pluginUri);
        }
    } catch (Exception e) {
        return new ContentProviderResult[0];
    }

    if (operations.size() > 0) {
        ContentProvider provider = getContentProvider(operations.get(0).getUri());
        if (provider != null) {
            return provider.applyBatch(operations);
        }
    }

    return new ContentProviderResult[0];
}
 
Example #14
Source File: EventLoader.java    From RememBirthday with GNU General Public License v3.0 6 votes vote down vote up
public synchronized static void deleteEventsFromContact(Context context, Contact contact) {
    ArrayList<ContentProviderOperation> operations = new ArrayList<>();
    try {
        for (CalendarEvent event : getEventsSavedForEachYear(context, contact)) {
            operations.add(ReminderProvider.deleteAll(context, event.getId()));
            operations.add(EventProvider.delete(event));
        }
        ContentProviderResult[] contentProviderResults =
                context.getContentResolver().applyBatch(CalendarContract.AUTHORITY, operations);
        for(ContentProviderResult contentProviderResult : contentProviderResults) {
            Log.d(TAG, contentProviderResult.toString());
            if (contentProviderResult.uri != null)
                Log.d(TAG, contentProviderResult.uri.toString());
        }
    } catch (RemoteException |OperationApplicationException |EventException e) {
        Log.e(TAG, "Unable to deleteById events : " + e.getMessage());
    }
}
 
Example #15
Source File: FDroidProvider.java    From fdroidclient with GNU General Public License v3.0 6 votes vote down vote up
@NonNull
@Override
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations)
        throws OperationApplicationException {
    ContentProviderResult[] result = null;
    applyingBatch = true;
    final SQLiteDatabase db = db();
    db.beginTransaction();
    try {
        result = super.applyBatch(operations);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        applyingBatch = false;
    }
    return result;
}
 
Example #16
Source File: ActivityItemsProvider.java    From GitJourney with Apache License 2.0 6 votes vote down vote up
/**
 * Apply the given set of {@link ContentProviderOperation}, executing inside
 * a {@link SQLiteDatabase} transaction. All changes will be rolled back if
 * any single one fails.
 */
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
        throws OperationApplicationException {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        final int numOperations = operations.size();
        final ContentProviderResult[] results = new ContentProviderResult[numOperations];
        for (int i = 0; i < numOperations; i++) {
            results[i] = operations.get(i).apply(this, results, i);
        }
        db.setTransactionSuccessful();
        return results;
    } finally {
        db.endTransaction();
    }
}
 
Example #17
Source File: SQLiteProvider.java    From android-atleap with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
    ContentProviderResult[] result = null;

    SQLiteDatabase db = this.getDatabaseHelper().getWritableDatabase();

    db.beginTransaction();
    try {
        result = super.applyBatch(operations);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
    return result;
}
 
Example #18
Source File: ContentProviderProxy1.java    From Neptune with Apache License 2.0 6 votes vote down vote up
@Override
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
    if (operations.size() > 0) {
        ContentProvider provider = getContentProvider(operations.get(0).getUri());
        if (provider != null) {
            try {
                for (ContentProviderOperation operation : operations) {
                    Uri pluginUri = Uri.parse(operation.getUri().getQueryParameter(IntentConstant.EXTRA_TARGET_URI_KEY));
                    ReflectionUtils.on(operation).set("mUri", pluginUri);
                }
                return provider.applyBatch(operations);
            } catch (Exception e) {
                return new ContentProviderResult[0];
            }
        }
    }
    return new ContentProviderResult[0];
}
 
Example #19
Source File: TransactionHelper.java    From CPOrm with MIT License 6 votes vote down vote up
public static void saveInTransaction(Context context, List<? extends CPDefaultRecord> records) throws RemoteException, OperationApplicationException {

        List<ContentProviderOperation> operations = prepareTransaction(context, records);
        ContentProviderResult[] contentProviderResults = CPOrm.applyPreparedOperations(operations);

        Map<Class, Long> referenceIds = new HashMap<>();

        for (int i = 0; i < contentProviderResults.length; i++) {

            ContentProviderResult result = contentProviderResults[i];
            CPDefaultRecord source = records.get(i);

            referenceIds.remove(source.getClass());
            if(result.uri != null && source.getId() == null && ContentUris.parseId(result.uri) != -1){

                source.setId(ContentUris.parseId(result.uri));
                referenceIds.put(source.getClass(), source.getId());
            }

            try {
                applyReferenceResults(source.getClass(), source, referenceIds);
            } catch (IllegalAccessException e) {
                CPOrmLog.e("Failed to apply back reference id's for uri " + result.uri);
            }
        }
    }
 
Example #20
Source File: Composite.java    From opentasks with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Context context, ContentProviderClient contentProviderClient, RowDataSnapshot<TaskContract.Instances> rowSnapshot, Uri taskUri) throws RemoteException, OperationApplicationException
{
    for (TaskAction action : mDelegates)
    {
        action.execute(context, contentProviderClient, rowSnapshot, taskUri);
    }
}
 
Example #21
Source File: DelayedAction.java    From opentasks with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Context context, ContentProviderClient contentProviderClient, RowDataSnapshot<TaskContract.Instances> rowSnapshot, Uri taskUri) throws RemoteException, OperationApplicationException
{
    AlarmManagerCompat.setExactAndAllowWhileIdle(
            (AlarmManager) context.getSystemService(Context.ALARM_SERVICE),
            AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis() + mDelayMillis,
            PendingIntent.getBroadcast(
                    context,
                    (int) ContentUris.parseId(taskUri),
                    new Intent(context, ActionReceiver.class).setAction(mAction).setData(taskUri),
                    PendingIntent.FLAG_UPDATE_CURRENT));
}
 
Example #22
Source File: PostUndoAction.java    From opentasks with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Context context, ContentProviderClient contentProviderClient, RowDataSnapshot<TaskContract.Instances> data, Uri taskUri) throws RemoteException, OperationApplicationException
{
    int id = (int) ContentUris.parseId(taskUri);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, ActionService.CHANNEL_DUE_DATES);
    builder.setContentTitle(context.getString(R.string.task_completed));
    builder.setSmallIcon(R.drawable.ic_notification);
    builder.setStyle(new NotificationCompat.DecoratedCustomViewStyle());
    builder.setDefaults(new NoSignal().value());

    final RemoteViews undoView = new RemoteViews(context.getPackageName(), R.layout.undo_notification);
    undoView.setTextViewText(R.id.description_text, context.getString(R.string.task_completed));

    undoView.setOnClickPendingIntent(
            R.id.status_bar_latest_event_content,
            PendingIntent.getBroadcast(
                    context,
                    id,
                    new Intent(context, ActionReceiver.class).setData(taskUri).setAction(ActionService.ACTION_UNDO_COMPLETE),
                    PendingIntent.FLAG_CANCEL_CURRENT));
    builder.setContent(undoView);

    // When the notification is cleared, we perform the destructive action
    builder.setDeleteIntent(PendingIntent.getBroadcast(
            context,
            id,
            new Intent(context, ActionReceiver.class).setData(taskUri).setAction(ActionService.ACTION_FINISH_COMPLETE),
            PendingIntent.FLAG_CANCEL_CURRENT));
    builder.setShowWhen(false);
    if (Build.VERSION.SDK_INT >= 21)
    {
        // don't execute this on Android 4, otherwise no notification will show up
        builder.setGroup(GROUP_UNDO);
    }
    builder.setColor(new ResourceColor(context, R.color.primary).argb());

    NotificationManagerCompat.from(context).notify("tasks.undo", id, builder.build());
}
 
Example #23
Source File: APEZProvider.java    From Alite with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ContentProviderResult[] applyBatch(
		ArrayList<ContentProviderOperation> operations)
		throws OperationApplicationException {
       initIfNecessary();
	return super.applyBatch(operations);
}
 
Example #24
Source File: DatabaseProvider.java    From arca-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public ContentProviderResult[] applyBatch(final ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
	final SQLiteDatabase database = getDatabase();
	database.beginTransaction();
	try {
		final ContentProviderResult[] results = super.applyBatch(operations);
		database.setTransactionSuccessful();
		return results;
	} finally {
		database.endTransaction();
	}
}
 
Example #25
Source File: LauncherProvider.java    From LB-Launcher with Apache License 2.0 5 votes vote down vote up
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
        throws OperationApplicationException {
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        ContentProviderResult[] result =  super.applyBatch(operations);
        db.setTransactionSuccessful();
        return result;
    } finally {
        db.endTransaction();
    }
}
 
Example #26
Source File: APEZProvider.java    From react-native-video with MIT License 5 votes vote down vote up
@Override
public ContentProviderResult[] applyBatch(
		ArrayList<ContentProviderOperation> operations)
		throws OperationApplicationException {
       initIfNecessary();
	return super.applyBatch(operations);
}
 
Example #27
Source File: CPOrmContentProvider.java    From CPOrm with MIT License 5 votes vote down vote up
@NonNull
@Override
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {

    if (debugEnabled) {
        CPOrmLog.d("********* Apply Batch **********");
        CPOrmLog.d("Operations Count: " + operations.size());
    }

    isBatchOperation.set(true);
    changedUri.set(new LinkedHashSet<Uri>());

    boolean success = false;
    ContentProviderResult[] contentProviderResults = null;
    SQLiteDatabase db = database.getWritableDatabase();
    try {
        db.beginTransactionNonExclusive();
        contentProviderResults = super.applyBatch(operations);
        db.setTransactionSuccessful();
        success = true;
        return contentProviderResults;
    } finally {
        db.endTransaction();

        if(success && changedUri.get() != null) {
            for (Uri uri : changedUri.get()) {

                if (uri != null) {
                    TableDetails tableDetails = uriMatcherHelper.getTableDetails(uri);
                    notifyChanges(uri, tableDetails);
                }
            }
        }
        isBatchOperation.set(false);
        changedUri.remove();
    }
}
 
Example #28
Source File: ActionService.java    From opentasks with Apache License 2.0 5 votes vote down vote up
@Override
protected void onHandleWork(@NonNull Intent intent)
{
    try
    {
        Uri instanceUri = intent.getData();
        if (instanceUri == null || instanceUri.getAuthority() == null)
        {
            throw new RuntimeException(String.format("Invalid task instance Uri %s", instanceUri));
        }

        ContentProviderClient contentProviderClient = getContentResolver().acquireContentProviderClient(instanceUri);
        for (RowSnapshot<TaskContract.Instances> snapshot : new QueryRowSet<>(
                new InstancesView<>(instanceUri.getAuthority(), contentProviderClient),
                new org.dmfs.android.contentpal.projections.Composite<>(
                        Id.PROJECTION,
                        EffectiveDueDate.PROJECTION,
                        TaskStart.PROJECTION,
                        TaskPin.PROJECTION,
                        EffectiveTaskColor.PROJECTION,
                        TaskTitle.PROJECTION,
                        TaskVersion.PROJECTION,
                        TaskIsClosed.PROJECTION),
                new EqArg<>(TaskContract.Instances._ID, ContentUris.parseId(instanceUri))))
        {
            resolveAction(intent.getAction()).execute(this, contentProviderClient, snapshot.values(), instanceUri);
        }
    }
    catch (RuntimeException | RemoteException | OperationApplicationException e)
    {
        Log.e("ActionService", String.format("unable to execute action %s", intent.getAction()), e);
    }
}
 
Example #29
Source File: ContactsFragment.java    From android-RuntimePermissions with Apache License 2.0 5 votes vote down vote up
/**
 * Accesses the Contacts content provider directly to insert a new contact.
 * <p>
 * The contact is called "__DUMMY ENTRY" and only contains a name.
 */
private void insertDummyContact() {
    // Two operations are needed to insert a new contact.
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(2);

    // First, set up a new raw contact.
    ContentProviderOperation.Builder op =
            ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null);
    operations.add(op.build());

    // Next, set the name for the contact.
    op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
            .withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                    DUMMY_CONTACT_NAME);
    operations.add(op.build());

    // Apply the operations.
    ContentResolver resolver = getActivity().getContentResolver();
    try {
        resolver.applyBatch(ContactsContract.AUTHORITY, operations);
    } catch (RemoteException | OperationApplicationException e) {
        Snackbar.make(mMessageText.getRootView(), "Could not add a new contact: " +
                e.getMessage(), Snackbar.LENGTH_LONG);
    }
}
 
Example #30
Source File: ContactsDatabase.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private void applyOperationsInBatches(@NonNull ContentResolver contentResolver,
                                      @NonNull String authority,
                                      @NonNull List<ContentProviderOperation> operations,
                                      int batchSize)
    throws OperationApplicationException, RemoteException
{
  List<List<ContentProviderOperation>> batches = Util.chunk(operations, batchSize);
  for (List<ContentProviderOperation> batch : batches) {
    contentResolver.applyBatch(authority, new ArrayList<>(batch));
  }
}