Example usage for android.content ContentResolver applyBatch

List of usage examples for android.content ContentResolver applyBatch

Introduction

In this page you can find the example usage for android.content ContentResolver applyBatch.

Prototype

public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
        @NonNull ArrayList<ContentProviderOperation> operations)
        throws RemoteException, OperationApplicationException 

Source Link

Document

Applies each of the ContentProviderOperation objects and returns an array of their results.

Usage

From source file:ch.berta.fabio.popularmovies.data.repositories.MovieRepositoryImpl.java

@Override
public Observable<ContentProviderResult[]> insertMovieLocal(@NonNull final Context context,
        @NonNull Movie movie) {/*from  www .  j av a2  s .co m*/
    return Observable.just(movie).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .map(new Func1<Movie, ArrayList<ContentProviderOperation>>() {
                @Override
                public ArrayList<ContentProviderOperation> call(Movie movie) {
                    return getInsertContentProviderOps(movie);
                }
            }).map(new Func1<ArrayList<ContentProviderOperation>, ContentProviderResult[]>() {
                @Override
                public ContentProviderResult[] call(ArrayList<ContentProviderOperation> ops) {
                    try {
                        final ContentResolver contentResolver = context.getApplicationContext()
                                .getContentResolver();
                        return contentResolver.applyBatch(MovieContract.CONTENT_AUTHORITY, ops);
                    } catch (Throwable t) {
                        throw Exceptions.propagate(t);
                    }
                }
            });
}

From source file:ch.berta.fabio.popularmovies.data.repositories.MovieRepositoryImpl.java

@Override
public Observable<ContentProviderResult[]> updateMovieLocal(@NonNull final Context context,
        @NonNull final MovieDetails movieDetails, final long movieRowId) {
    return Observable.just(movieDetails).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .map(new Func1<MovieDetails, ArrayList<ContentProviderOperation>>() {
                @Override//from w w  w  . j a  va  2s .com
                public ArrayList<ContentProviderOperation> call(MovieDetails movieDetails) {
                    return getUpdateContentProvidersOps(movieDetails, movieRowId);
                }
            }).map(new Func1<ArrayList<ContentProviderOperation>, ContentProviderResult[]>() {
                @Override
                public ContentProviderResult[] call(
                        ArrayList<ContentProviderOperation> contentProviderOperations) {
                    try {
                        final ContentResolver contentResolver = context.getApplicationContext()
                                .getContentResolver();
                        return contentResolver.applyBatch(MovieContract.CONTENT_AUTHORITY,
                                contentProviderOperations);
                    } catch (Throwable t) {
                        throw Exceptions.propagate(t);
                    }
                }
            });
}

From source file:com.granita.tasks.notification.NotificationActionIntentService.java

private void markCompleted(Uri taskUri) {
    ContentResolver contentResolver = getContentResolver();
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(1);
    ContentProviderOperation.Builder operation = ContentProviderOperation.newUpdate(taskUri);
    operation.withValue(Tasks.STATUS, Tasks.STATUS_COMPLETED);
    operations.add(operation.build());/*from w  ww .jav  a2s . c o m*/
    try {
        contentResolver.applyBatch(mAuthority, operations);
    } catch (RemoteException e) {
        Log.e(TAG, "Remote exception during complete task action");
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        Log.e(TAG, "Unable to mark task completed: " + taskUri);
        e.printStackTrace();
    }
}

From source file:com.manning.androidhacks.hack043.service.SQLContentProviderService.java

@Override
protected void onHandleIntent(Intent intent) {
    Builder builder = null;/*from  w  ww  .j  av a 2  s  .c o m*/
    ContentResolver contentResolver = getContentResolver();
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    builder = ContentProviderOperation.newDelete(MySQLContentProvider.CONTENT_URI);
    operations.add(builder.build());

    for (int i = 1; i <= 100; i++) {
        ContentValues cv = new ContentValues();
        cv.put(MySQLContentProvider.COLUMN_TEXT, "" + i);

        builder = ContentProviderOperation.newInsert(MySQLContentProvider.CONTENT_URI);
        builder.withValues(cv);

        operations.add(builder.build());
    }

    try {
        contentResolver.applyBatch(MySQLContentProvider.AUTHORITY, operations);
    } catch (RemoteException e) {
        Log.e(TAG, "Couldn't apply batch: " + e.getMessage());
    } catch (OperationApplicationException e) {
        Log.e(TAG, "Couldn't apply batch: " + e.getMessage());
    }

}

From source file:com.manning.androidhacks.hack043.service.BatchService.java

@Override
protected void onHandleIntent(Intent intent) {
    Builder builder = null;/*from  w ww.  j  a  va  2 s.  c  o m*/
    ContentResolver contentResolver = getContentResolver();
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    builder = ContentProviderOperation.newDelete(BatchNumbersContentProvider.CONTENT_URI);
    operations.add(builder.build());

    for (int i = 1; i <= 100; i++) {
        ContentValues cv = new ContentValues();
        cv.put(NoBatchNumbersContentProvider.COLUMN_TEXT, "" + i);

        builder = ContentProviderOperation.newInsert(BatchNumbersContentProvider.CONTENT_URI);
        builder.withValues(cv);

        operations.add(builder.build());
    }

    try {
        contentResolver.applyBatch(BatchNumbersContentProvider.AUTHORITY, operations);
    } catch (RemoteException e) {
        Log.e(TAG, "Couldn't apply batch: " + e.getMessage());
    } catch (OperationApplicationException e) {
        Log.e(TAG, "Couldn't apply batch: " + e.getMessage());
    }

}

From source file:org.dmfs.tasks.notification.NotificationUpdaterService.java

private void markCompleted(Uri taskUri) {
    ContentResolver contentResolver = getContentResolver();
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(1);
    ContentProviderOperation.Builder operation = ContentProviderOperation.newUpdate(taskUri);
    operation.withValue(Tasks.STATUS, Tasks.STATUS_COMPLETED);
    operation.withValue(Tasks.PINNED, false);
    operations.add(operation.build());/* www.j a  v a 2  s .  co m*/
    try {
        contentResolver.applyBatch(mAuthority, operations);
    } catch (RemoteException e) {
        Log.e(TAG, "Remote exception during complete task action");
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        Log.e(TAG, "Unable to mark task completed: " + taskUri);
        e.printStackTrace();
    }
}

From source file:saschpe.birthdays.service.CalendarSyncService.java

/**
 * Returns birthday calendar ID./*from w ww. j  av a2s.co m*/
 *
 * If no calendar is present, a new one is created.
 *
 * @return calendar id
 */
public static long getCalendar(Context context) {
    final Uri calenderUri = getCalendarUri(context, CalendarContract.Calendars.CONTENT_URI);

    final String selection = CalendarContract.Calendars.ACCOUNT_NAME + " = ? AND "
            + CalendarContract.Calendars.ACCOUNT_TYPE + " = ? AND " + CalendarContract.Calendars.NAME + " = ?";
    final String calendarName = context.getString(R.string.calendar_name);

    ContentResolver cr = context.getContentResolver();
    Cursor cursor = cr.query(calenderUri, new String[] { BaseColumns._ID }, selection, new String[] {
            context.getString(R.string.app_name), context.getString(R.string.account_type), calendarName },
            null);

    if (cursor != null && cursor.moveToNext()) {
        // Yay, calendar exists already. Just return it's id.
        long calendarId = cursor.getLong(0);
        cursor.close();
        return calendarId;
    } else {
        if (cursor != null) {
            cursor.close();
        }

        // So we've got to create a calendar first before we can return it's id.
        ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(calenderUri);
        builder.withValue(CalendarContract.Calendars.ACCOUNT_NAME, context.getString(R.string.app_name));
        builder.withValue(CalendarContract.Calendars.ACCOUNT_TYPE, context.getString(R.string.account_type));
        builder.withValue(CalendarContract.Calendars.NAME, calendarName);
        builder.withValue(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
                context.getString(R.string.birthdays_and_anniversaries));
        builder.withValue(CalendarContract.Calendars.CALENDAR_COLOR,
                PreferencesHelper.getCalendarColor(context));
        builder.withValue(CalendarContract.Calendars.SYNC_EVENTS, PreferencesHelper.isCalendarSynced(context));
        builder.withValue(CalendarContract.Calendars.VISIBLE, 1);
        if (BuildConfig.DEBUG) {
            builder.withValue(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
                    CalendarContract.Calendars.CAL_ACCESS_EDITOR);
        } else {
            builder.withValue(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
                    CalendarContract.Calendars.CAL_ACCESS_READ);
        }
        builder.withValue(CalendarContract.Calendars.OWNER_ACCOUNT, context.getString(R.string.app_name));

        ArrayList<ContentProviderOperation> operations = new ArrayList<>();
        operations.add(builder.build());
        try {
            cr.applyBatch(CalendarContract.AUTHORITY, operations);
            Log.d(TAG, "Created calendar " + calendarName);
        } catch (RemoteException e) {
            Log.e(TAG, "Unable to create new calendar!", e);
            return -1;
        } catch (OperationApplicationException e) {
            Log.e(TAG, "Unable to create new calendar!", e);
            return -2;
        }

        // Try once again, this time we should find something in the database
        return getCalendar(context);
    }
}

From source file:com.google.samples.apps.iosched.service.SessionCalendarService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (!permissionsAlreadyGranted()) {
        LOGW(TAG, "Calendar permission not granted.");
        return;//ww w . j  a v a 2  s  .  c  o  m
    }

    final String action = intent.getAction();
    LOGD(TAG, "Received intent: " + action);

    final ContentResolver resolver = getContentResolver();

    boolean isAddEvent = false;

    if (ACTION_ADD_SESSION_CALENDAR.equals(action)) {
        isAddEvent = true;

    } else if (ACTION_REMOVE_SESSION_CALENDAR.equals(action)) {
        isAddEvent = false;

    } else if (ACTION_UPDATE_ALL_SESSIONS_CALENDAR.equals(action) && SettingsUtils.shouldSyncCalendar(this)) {
        try {
            getContentResolver().applyBatch(CalendarContract.AUTHORITY,
                    processAllSessionsCalendar(resolver, getCalendarId(intent)));
            sendBroadcast(new Intent(SessionCalendarService.ACTION_UPDATE_ALL_SESSIONS_CALENDAR_COMPLETED));
        } catch (RemoteException | OperationApplicationException e) {
            LOGE(TAG, "Error adding all sessions to Google Calendar", e);
        }

    } else if (ACTION_CLEAR_ALL_SESSIONS_CALENDAR.equals(action)) {
        try {
            getContentResolver().applyBatch(CalendarContract.AUTHORITY,
                    processClearAllSessions(resolver, getCalendarId(intent)));
        } catch (RemoteException | OperationApplicationException e) {
            LOGE(TAG, "Error clearing all sessions from Google Calendar", e);
        }

    } else {
        return;
    }

    final Uri uri = intent.getData();
    final Bundle extras = intent.getExtras();
    if (uri == null || extras == null || !SettingsUtils.shouldSyncCalendar(this)) {
        return;
    }

    try {
        resolver.applyBatch(CalendarContract.AUTHORITY,
                processSessionCalendar(resolver, getCalendarId(intent), isAddEvent, uri,
                        extras.getLong(EXTRA_SESSION_START), extras.getLong(EXTRA_SESSION_END),
                        extras.getString(EXTRA_SESSION_TITLE), extras.getString(EXTRA_SESSION_ROOM)));
    } catch (RemoteException | OperationApplicationException e) {
        LOGE(TAG, "Error adding session to Google Calendar", e);
    }
}

From source file:com.android.contacts.ContactSaveService.java

/** Returns true if the batch was successfully applied and false otherwise. */
private boolean applyOperations(ContentResolver resolver, ArrayList<ContentProviderOperation> operations) {
    try {//from w w w  . j a v  a 2s. c om
        final ContentProviderResult[] result = resolver.applyBatch(ContactsContract.AUTHORITY, operations);
        for (int i = 0; i < result.length; ++i) {
            // if no rows were modified in the operation then we count it as fail.
            if (result[i].count < 0) {
                throw new OperationApplicationException();
            }
        }
        return true;
    } catch (RemoteException | OperationApplicationException e) {
        FeedbackHelper.sendFeedback(this, TAG, "Failed to apply aggregation exception batch", e);
        showToast(R.string.contactSavedErrorToast);
        return false;
    }
}

From source file:com.android.contacts.ContactSaveService.java

private void createRawContact(Intent intent) {
    String accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME);
    String accountType = intent.getStringExtra(EXTRA_ACCOUNT_TYPE);
    String dataSet = intent.getStringExtra(EXTRA_DATA_SET);
    List<ContentValues> valueList = intent.getParcelableArrayListExtra(EXTRA_CONTENT_VALUES);
    Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT);

    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
    operations.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
            .withValue(RawContacts.ACCOUNT_NAME, accountName).withValue(RawContacts.ACCOUNT_TYPE, accountType)
            .withValue(RawContacts.DATA_SET, dataSet).build());

    int size = valueList.size();
    for (int i = 0; i < size; i++) {
        ContentValues values = valueList.get(i);
        values.keySet().retainAll(ALLOWED_DATA_COLUMNS);
        operations.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
                .withValueBackReference(Data.RAW_CONTACT_ID, 0).withValues(values).build());
    }/*ww w .  j  a va  2  s  . c o  m*/

    ContentResolver resolver = getContentResolver();
    ContentProviderResult[] results;
    try {
        results = resolver.applyBatch(ContactsContract.AUTHORITY, operations);
    } catch (Exception e) {
        throw new RuntimeException("Failed to store new contact", e);
    }

    Uri rawContactUri = results[0].uri;
    callbackIntent.setData(RawContacts.getContactLookupUri(resolver, rawContactUri));

    deliverCallback(callbackIntent);
}