Example usage for android.content ContentProviderOperation newUpdate

List of usage examples for android.content ContentProviderOperation newUpdate

Introduction

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

Prototype

public static Builder newUpdate(Uri uri) 

Source Link

Document

Create a Builder suitable for building an update ContentProviderOperation .

Usage

From source file:org.mythtv.service.dvr.v25.RecordingRuleHelperV25.java

private void processRecordingRule(final Context context, final LocationProfile locationProfile,
        ArrayList<ContentProviderOperation> ops, org.mythtv.services.api.v025.beans.RecRule recRule) {
    Log.d(TAG, "processRecordingRule : enter");

    String recRuleSelection = RecordingRuleConstants.FIELD_REC_RULE_ID + " = ?";

    recRuleSelection = appendLocationHostname(context, locationProfile, recRuleSelection,
            RecordingRuleConstants.TABLE_NAME);

    ContentValues recRuleValues = convertRecRuleToContentValues(locationProfile, recRule);
    Cursor recRuleCursor = context.getContentResolver().query(RecordingRuleConstants.CONTENT_URI,
            recRuleProjection, recRuleSelection, new String[] { String.valueOf(recRule.getId()) }, null);
    if (recRuleCursor.moveToFirst()) {
        Long id = recRuleCursor.getLong(recRuleCursor.getColumnIndexOrThrow(RecordingRuleConstants._ID));
        Log.v(TAG, "processRecordingRule : updating recRule " + id + ":" + recRule.getId() + ":"
                + recRule.getTitle());/*from   w  w w .java 2 s.co  m*/

        ops.add(ContentProviderOperation
                .newUpdate(ContentUris.withAppendedId(RecordingRuleConstants.CONTENT_URI, id))
                .withValues(recRuleValues).build());

    } else {
        Log.v(TAG, "processRecordingRule : adding recRule " + recRule.getId() + ":" + recRule.getTitle());

        ops.add(ContentProviderOperation.newInsert(RecordingRuleConstants.CONTENT_URI).withValues(recRuleValues)
                .build());

    }
    recRuleCursor.close();

    Log.d(TAG, "processRecordingRule : exit");
}

From source file:org.mythtv.service.dvr.v26.RecordingRuleHelperV26.java

private void processRecordingRule(final Context context, final LocationProfile locationProfile,
        ArrayList<ContentProviderOperation> ops, org.mythtv.services.api.v026.beans.RecRule recRule) {
    Log.d(TAG, "processRecordingRule : enter");

    String recRuleSelection = RecordingRuleConstants.FIELD_REC_RULE_ID + " = ?";

    recRuleSelection = appendLocationHostname(context, locationProfile, recRuleSelection,
            RecordingRuleConstants.TABLE_NAME);

    ContentValues recRuleValues = convertRecRuleToContentValues(locationProfile, recRule);
    Cursor recRuleCursor = context.getContentResolver().query(RecordingRuleConstants.CONTENT_URI,
            recRuleProjection, recRuleSelection, new String[] { String.valueOf(recRule.getId()) }, null);
    if (recRuleCursor.moveToFirst()) {
        Long id = recRuleCursor.getLong(recRuleCursor.getColumnIndexOrThrow(RecordingRuleConstants._ID));
        Log.v(TAG, "processRecordingRule : updating recRule " + id + ":" + recRule.getId() + ":"
                + recRule.getTitle());/*  w  w  w .ja  v  a2 s.  c o m*/

        ops.add(ContentProviderOperation
                .newUpdate(ContentUris.withAppendedId(RecordingRuleConstants.CONTENT_URI, id))
                .withValues(recRuleValues).build());

    } else {
        Log.v(TAG, "processRecordingRule : adding recRule " + recRule.getId() + ":" + recRule.getTitle());

        ops.add(ContentProviderOperation.newInsert(RecordingRuleConstants.CONTENT_URI).withValues(recRuleValues)
                .build());

    }
    recRuleCursor.close();

    Log.d(TAG, "processRecordingRule : exit");
}

From source file:org.mythtv.service.dvr.v27.RecordingRuleHelperV27.java

private void processRecordingRule(final Context context, final LocationProfile locationProfile,
        ArrayList<ContentProviderOperation> ops, org.mythtv.services.api.v027.beans.RecRule recRule) {
    Log.d(TAG, "processRecordingRule : enter");

    String recRuleSelection = RecordingRuleConstants.FIELD_REC_RULE_ID + " = ?";

    recRuleSelection = appendLocationHostname(context, locationProfile, recRuleSelection,
            RecordingRuleConstants.TABLE_NAME);

    ContentValues recRuleValues = convertRecRuleToContentValues(locationProfile, recRule);
    Cursor recRuleCursor = context.getContentResolver().query(RecordingRuleConstants.CONTENT_URI,
            recRuleProjection, recRuleSelection, new String[] { String.valueOf(recRule.getId()) }, null);
    if (recRuleCursor.moveToFirst()) {
        Long id = recRuleCursor.getLong(recRuleCursor.getColumnIndexOrThrow(RecordingRuleConstants._ID));
        Log.v(TAG, "processRecordingRule : updating recRule " + id + ":" + recRule.getId() + ":"
                + recRule.getTitle());/*www  . j a va2 s . c o  m*/

        ops.add(ContentProviderOperation
                .newUpdate(ContentUris.withAppendedId(RecordingRuleConstants.CONTENT_URI, id))
                .withValues(recRuleValues).build());

    } else {
        Log.v(TAG, "processRecordingRule : adding recRule " + recRule.getId() + ":" + recRule.getTitle());

        ops.add(ContentProviderOperation.newInsert(RecordingRuleConstants.CONTENT_URI).withValues(recRuleValues)
                .build());

    }
    recRuleCursor.close();

    Log.d(TAG, "processRecordingRule : exit");
}

From source file:org.m2x.rssreader.service.FetcherService.java

private void downloadAllImages() {
    ContentResolver cr = MainApplication.getContext().getContentResolver();
    Cursor cursor = cr.query(TaskColumns.CONTENT_URI,
            new String[] { TaskColumns._ID, TaskColumns.ENTRY_ID, TaskColumns.IMG_URL_TO_DL,
                    TaskColumns.NUMBER_ATTEMPT },
            TaskColumns.IMG_URL_TO_DL + Constants.DB_IS_NOT_NULL, null, null);

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

    while (cursor.moveToNext()) {
        long taskId = cursor.getLong(0);
        long entryId = cursor.getLong(1);
        String imgPath = cursor.getString(2);
        int nbAttempt = 0;
        if (!cursor.isNull(3)) {
            nbAttempt = cursor.getInt(3);
        }/*from   w  ww  .  j  av a2 s  .c o  m*/

        try {
            NetworkUtils.downloadImage(entryId, imgPath);

            // If we are here, everything is OK
            operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            cr.notifyChange(EntryColumns.CONTENT_URI(entryId), null); // To refresh the view
        } catch (Exception e) {
            if (nbAttempt + 1 > MAX_TASK_ATTEMPT) {
                operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            } else {
                ContentValues values = new ContentValues();
                values.put(TaskColumns.NUMBER_ATTEMPT, nbAttempt + 1);
                operations.add(ContentProviderOperation.newUpdate(TaskColumns.CONTENT_URI(taskId))
                        .withValues(values).build());
            }
        }
    }

    cursor.close();

    if (!operations.isEmpty()) {
        try {
            cr.applyBatch(FeedData.AUTHORITY, operations);
        } catch (Throwable ignored) {
        }
    }
}

From source file:com.granita.icloudcalsync.resource.LocalCollection.java

/** Enqueues updating an existing resource in the local collection. The resource will be found by 
 * the remote file name and all data will be updated. Requires commit(). */
public void updateByRemoteName(Resource remoteResource) throws LocalStorageException {
    T localResource = findByRemoteName(remoteResource.getName(), false);
    pendingOperations//from   w ww. j  av a  2  s .c  o  m
            .add(buildEntry(
                    ContentProviderOperation
                            .newUpdate(ContentUris.withAppendedId(entriesURI(), localResource.getLocalID())),
                    remoteResource, true).withValue(entryColumnETag(), remoteResource.getETag())
                            .withYieldAllowed(true).build());

    removeDataRows(localResource);
    addDataRows(remoteResource, localResource.getLocalID(), -1);
}

From source file:com.example.android.basicsyncadapter.SyncAdapter.java

/**
 * Read XML from an input stream, storing it into the content provider.
 *
 * <p>This is where incoming data is persisted, committing the results of a sync. In order to
 * minimize (expensive) disk operations, we compare incoming data with what's already in our
 * database, and compute a merge. Only changes (insert/update/delete) will result in a database
 * write./*from  ww  w  . java  2s.c om*/
 *
 * <p>As an additional optimization, we use a batch operation to perform all database writes at
 * once.
 *
 * <p>Merge strategy:
 * 1. Get cursor to all items in feed<br/>
 * 2. For each item, check if it's in the incoming data.<br/>
 *    a. YES: Remove from "incoming" list. Check if data has mutated, if so, perform
 *            database UPDATE.<br/>
 *    b. NO: Schedule DELETE from database.<br/>
 * (At this point, incoming database only contains missing items.)<br/>
 * 3. For any items remaining in incoming list, ADD to database.
 */
public void updateLocalFeedData(final InputStream stream, final SyncResult syncResult) throws IOException,
        XmlPullParserException, RemoteException, OperationApplicationException, ParseException {
    //final FeedParser feedParser = new FeedParser();
    final CAPFeedParser feedParser = new CAPFeedParser();
    final ContentResolver contentResolver = getContext().getContentResolver();

    //Log.i(TAG, "Parsing stream as Atom feed");
    final List<CAPFeedParser.Entry> entries = feedParser.parse(stream);
    Log.i(TAG, "Parsing complete. Found " + entries.size() + " entries");

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

    // Build hash table of incoming entries
    HashMap<String, CAPFeedParser.Entry> entryMap = new HashMap<String, CAPFeedParser.Entry>();
    for (CAPFeedParser.Entry e : entries) {
        entryMap.put(e.id, e);
    }

    // Get list of all items
    //Log.i(TAG, "Fetching local entries for merge");
    Uri uri = FeedContract.Entry.CONTENT_URI; // Get all entries
    Cursor c = contentResolver.query(uri, PROJECTION, null, null, null);
    assert c != null;
    //Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution...");

    // Find stale data
    int id;
    String entryId;
    String title;
    String description;
    String headline;
    String url;
    String areas;
    String issued;
    while (c.moveToNext()) {
        syncResult.stats.numEntries++;

        id = c.getInt(COLUMN_ID);
        entryId = c.getString(COLUMN_ENTRY_ID);
        title = c.getString(COLUMN_TITLE);
        description = c.getString(COLUMN_DESCRIPTION);
        headline = c.getString(COLUMN_HEADLINE);
        areas = c.getString(COLUMN_AREAS);
        url = c.getString(COLUMN_LINK);
        issued = c.getString(COLUMN_ISSUED);

        CAPFeedParser.Entry match = entryMap.get(entryId);
        if (match != null) {
            // Entry exists. Remove from entry map to prevent insert later.
            entryMap.remove(entryId);
            // Check to see if the entry needs to be updated
            Uri existingUri = FeedContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id))
                    .build();
            if ((match.title != null && !match.title.equals(title))
                    || (match.link != null && !match.link.equals(url)) || (match.issued != issued)) {
                // Update existing record
                //Log.i(TAG, "Scheduling update: " + existingUri);
                batch.add(ContentProviderOperation.newUpdate(existingUri)
                        .withValue(FeedContract.Entry.COLUMN_NAME_TITLE, title)
                        .withValue(FeedContract.Entry.COLUMN_NAME_DESCRIPTION, description)
                        .withValue(FeedContract.Entry.COLUMN_NAME_HEADLINE, headline)
                        .withValue(FeedContract.Entry.COLUMN_NAME_ISSUED, issued)
                        .withValue(FeedContract.Entry.COLUMN_NAME_LINK, url)
                        .withValue(FeedContract.Entry.COLUMN_NAME_AREAS, areas).build());
                syncResult.stats.numUpdates++;
            } else {
                //Log.i(TAG, "No action: " + existingUri);
            }
        } else {
            // Entry doesn't exist. Remove it from the database.
            Uri deleteUri = FeedContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)).build();
            //Log.i(TAG, "Scheduling delete: " + deleteUri);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            syncResult.stats.numDeletes++;
        }
    }
    c.close();

    // Add new items
    for (CAPFeedParser.Entry e : entryMap.values()) {
        //Log.i(TAG, "Scheduling insert: entry_id=" + e.id);
        batch.add(ContentProviderOperation.newInsert(FeedContract.Entry.CONTENT_URI)
                .withValue(FeedContract.Entry.COLUMN_NAME_ENTRY_ID, e.id)
                .withValue(FeedContract.Entry.COLUMN_NAME_TITLE, e.title)
                .withValue(FeedContract.Entry.COLUMN_NAME_DESCRIPTION, e.description)
                .withValue(FeedContract.Entry.COLUMN_NAME_HEADLINE, e.headline)
                .withValue(FeedContract.Entry.COLUMN_NAME_ISSUED, e.issued)
                .withValue(FeedContract.Entry.COLUMN_NAME_LINK, e.link)
                .withValue(FeedContract.Entry.COLUMN_NAME_AREAS, e.areas).build());
        syncResult.stats.numInserts++;
    }
    //Log.i(TAG, "Merge solution ready. Applying batch update");
    mContentResolver.applyBatch(FeedContract.CONTENT_AUTHORITY, batch);
    mContentResolver.notifyChange(FeedContract.Entry.CONTENT_URI, // URI where data was modified
            null, // No local observer
            false); // IMPORTANT: Do not sync to network
    // This sample doesn't support uploads, but if *your* code does, make sure you set
    // syncToNetwork=false in the line above to prevent duplicate syncs.
}

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

@Override
public void clearDirty(Resource resource) {
    super.clearDirty(resource);

    // clear dirty flag of all exceptions of this event
    pendingOperations.add(ContentProviderOperation.newUpdate(entriesURI()).withValue(Events.DIRTY, 0)
            .withSelection(Events.ORIGINAL_ID + "=?", new String[] { String.valueOf(resource.getLocalID()) })
            .build());//ww w . j  a  v a2s.c o  m
}

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

/** Updates an existing resource in the local collection. The resource will be found by
 * the remote file name and all data will be updated. */
public void updateByRemoteName(Resource remoteResource) throws LocalStorageException {
    T localResource = findByRemoteName(remoteResource.getName(), false);
    pendingOperations//from  w  w w  . j a  v a 2  s  .  c o  m
            .add(buildEntry(
                    ContentProviderOperation
                            .newUpdate(ContentUris.withAppendedId(entriesURI(), localResource.getLocalID())),
                    remoteResource, true).withValue(entryColumnETag(), remoteResource.getETag())
                            .withYieldAllowed(true).build());

    removeDataRows(localResource);
    addDataRows(remoteResource, localResource.getLocalID(), -1);
    commit();
}

From source file:org.linphone.compatibility.ApiFivePlus.java

public static void updateSipAddressForContact(ArrayList<ContentProviderOperation> ops, String oldSipAddress,
        String newSipAddress, String contactID) {
    String select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='"
            + ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE + "' AND "
            + ContactsContract.CommonDataKinds.Im.DATA + "=?";
    String[] args = new String[] { String.valueOf(contactID), oldSipAddress };

    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(select, args)
            .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.Im.DATA, newSipAddress).build());
}

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

/**
 * Adds or removes a single session to/from the specified Google Calendar.
 *///from   w  ww  .  j  a  v a 2s .co  m
private ArrayList<ContentProviderOperation> processSessionCalendar(final ContentResolver resolver,
        final long calendarId, final boolean isAddEvent, final Uri sessionUri, final long sessionBlockStart,
        final long sessionBlockEnd, final String sessionTitle, final String sessionRoom) {
    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();

    // Unable to find the Calendar associated with the user or permissions were revoked.
    if (calendarId == INVALID_CALENDAR_ID || !permissionsAlreadyGranted()) {
        return batch;
    }

    final String calendarEventTitle = makeCalendarEventTitle(sessionTitle);

    Cursor cursor;
    ContentValues values = new ContentValues();

    // Add Calendar event.
    if (isAddEvent) {
        if (sessionBlockStart == 0L || sessionBlockEnd == 0L || sessionTitle == null) {
            LOGW(TAG, "Unable to add a Calendar event due to insufficient input parameters.");
            return batch;
        }

        // Check if the calendar event exists first.  If it does, we don't want to add a
        // duplicate one.
        //noinspection MissingPermission
        cursor = resolver.query(CalendarContract.Events.CONTENT_URI, // URI
                new String[] { CalendarContract.Events._ID }, // Projection
                CalendarContract.Events.CALENDAR_ID + "=? and " // Selection
                        + CalendarContract.Events.TITLE + "=? and " + CalendarContract.Events.DTSTART
                        + ">=? and " + CalendarContract.Events.DTEND + "<=?",
                new String[] { // Selection args
                        Long.valueOf(calendarId).toString(), calendarEventTitle,
                        Long.toString(Config.CONFERENCE_START_MILLIS),
                        Long.toString(Config.CONFERENCE_END_MILLIS) },
                null);

        long newEventId = -1;

        if (cursor != null && cursor.moveToFirst()) {
            // Calendar event already exists for this session.
            newEventId = cursor.getLong(0);
            cursor.close();

            // Data fix (workaround):
            batch.add(ContentProviderOperation.newUpdate(CalendarContract.Events.CONTENT_URI)
                    .withValue(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID())
                    .withSelection(CalendarContract.Events._ID + "=?",
                            new String[] { Long.valueOf(newEventId).toString() })
                    .build());
            // End data fix.

        } else {
            // Calendar event doesn't exist, create it.

            // NOTE: we can't use batch processing here because we need the result of
            // the insert.
            values.clear();
            values.put(CalendarContract.Events.DTSTART, sessionBlockStart);
            values.put(CalendarContract.Events.DTEND, sessionBlockEnd);
            values.put(CalendarContract.Events.EVENT_LOCATION, sessionRoom);
            values.put(CalendarContract.Events.TITLE, calendarEventTitle);
            values.put(CalendarContract.Events.CALENDAR_ID, calendarId);
            values.put(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID());
            @SuppressWarnings("MissingPermission")
            Uri eventUri = resolver.insert(CalendarContract.Events.CONTENT_URI, values);
            String eventId = eventUri.getLastPathSegment();
            if (eventId == null) {
                return batch; // Should be empty at this point
            }

            newEventId = Long.valueOf(eventId);
            // Since we're adding session reminder to system notification, we're not creating
            // Calendar event reminders.  If we were to create Calendar event reminders, this
            // is how we would do it.
            //values.put(CalendarContract.Reminders.EVENT_ID, Integer.valueOf(eventId));
            //values.put(CalendarContract.Reminders.MINUTES, 10);
            //values.put(CalendarContract.Reminders.METHOD,
            //        CalendarContract.Reminders.METHOD_ALERT); // Or default?
            //cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
            //values.clear();
        }

        // Update the session in our own provider with the newly created calendar event ID.
        values.clear();
        values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, newEventId);
        resolver.update(sessionUri, values, null, null);

    } else {
        // Remove Calendar event, if exists.

        // Get the event calendar id.
        cursor = resolver.query(sessionUri, new String[] { ScheduleContract.Sessions.SESSION_CAL_EVENT_ID },
                null, null, null);
        long calendarEventId = -1;
        if (cursor != null && cursor.moveToFirst()) {
            calendarEventId = cursor.getLong(0);
            cursor.close();
        }

        // Try to remove the Calendar Event based on key.  If successful, move on;
        // otherwise, remove the event based on Event title.
        int affectedRows = 0;
        if (calendarEventId != -1) {
            //noinspection MissingPermission
            affectedRows = resolver.delete(CalendarContract.Events.CONTENT_URI,
                    CalendarContract.Events._ID + "=?",
                    new String[] { Long.valueOf(calendarEventId).toString() });
        }

        if (affectedRows == 0) {
            //noinspection MissingPermission
            resolver.delete(CalendarContract.Events.CONTENT_URI,
                    String.format("%s=? and %s=? and %s=? and %s=?", CalendarContract.Events.CALENDAR_ID,
                            CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART,
                            CalendarContract.Events.DTEND),
                    new String[] { Long.valueOf(calendarId).toString(), calendarEventTitle,
                            Long.valueOf(sessionBlockStart).toString(),
                            Long.valueOf(sessionBlockEnd).toString() });
        }

        // Remove the session and calendar event association.
        values.clear();
        values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, (Long) null);
        resolver.update(sessionUri, values, null, null);
    }

    return batch;
}