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:at.bitfire.davdroid.resource.LocalAddressBook.java

@Override
public int commit() throws LocalStorageException {
    int affected = super.commit();

    // update group details for groups we have just created
    Uri groupsUri = syncAdapterURI(Groups.CONTENT_URI);
    try {/*from   w  w w .j  av a  2 s.co m*/
        // newly created groups don't have a TITLE
        @Cleanup
        Cursor cursor = providerClient.query(groupsUri, new String[] { Groups.SOURCE_ID },
                Groups.TITLE + " IS NULL", null, null);
        while (cursor != null && cursor.moveToNext()) {
            // found group, set TITLE to SOURCE_ID and other details
            String sourceID = cursor.getString(0);
            pendingOperations.add(ContentProviderOperation.newUpdate(groupsUri)
                    .withSelection(Groups.SOURCE_ID + "=?", new String[] { sourceID })
                    .withValue(Groups.TITLE, sourceID).withValue(Groups.GROUP_VISIBLE, 1).build());
            affected += super.commit();
        }
    } catch (RemoteException e) {
        throw new LocalStorageException("Couldn't update group names", e);
    }

    return affected;
}

From source file:org.c99.SyncProviderDemo.ContactsSyncAdapterService.java

private static void updateContactStatus(ArrayList<ContentProviderOperation> operationList, long rawContactId,
        String status) {// w ww . ja  va2s  .  c o  m
    Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
    Uri entityUri = Uri.withAppendedPath(rawContactUri, Entity.CONTENT_DIRECTORY);
    Cursor c = mContentResolver.query(entityUri,
            new String[] { RawContacts.SOURCE_ID, Entity.DATA_ID, Entity.MIMETYPE, Entity.DATA1 }, null, null,
            null);
    try {
        while (c.moveToNext()) {
            if (!c.isNull(1)) {
                String mimeType = c.getString(2);

                if (mimeType.equals("vnd.android.cursor.item/vnd.org.c99.SyncProviderDemo.profile")) {
                    ContentProviderOperation.Builder builder = ContentProviderOperation
                            .newInsert(ContactsContract.StatusUpdates.CONTENT_URI);
                    builder.withValue(ContactsContract.StatusUpdates.DATA_ID, c.getLong(1));
                    builder.withValue(ContactsContract.StatusUpdates.STATUS, status);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_RES_PACKAGE,
                            "org.c99.SyncProviderDemo");
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_LABEL, R.string.app_name);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_ICON, R.drawable.logo);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_TIMESTAMP,
                            System.currentTimeMillis());
                    operationList.add(builder.build());

                    //Only change the text of our custom entry to the status message pre-Honeycomb, as the newer contacts app shows
                    //statuses elsewhere
                    if (Integer.decode(Build.VERSION.SDK) < 11) {
                        builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
                        builder.withSelection(BaseColumns._ID + " = '" + c.getLong(1) + "'", null);
                        builder.withValue(ContactsContract.Data.DATA3, status);
                        operationList.add(builder.build());
                    }
                }
            }
        }
    } finally {
        c.close();
    }
}

From source file:at.bitfire.davdroid.mirakel.resource.LocalAddressBook.java

@Override
public void commit() throws LocalStorageException {
    super.commit();

    // update group details for groups we have just created
    Uri groupsUri = syncAdapterURI(Groups.CONTENT_URI);
    try {/*from w  ww.  ja  va 2s  .  c om*/
        // newly created groups don't have a TITLE
        @Cleanup
        Cursor cursor = providerClient.query(groupsUri, new String[] { Groups.SOURCE_ID },
                Groups.TITLE + " IS NULL", null, null);
        while (cursor != null && cursor.moveToNext()) {
            // found group, set TITLE to SOURCE_ID and other details
            String sourceID = cursor.getString(0);
            pendingOperations.add(ContentProviderOperation.newUpdate(groupsUri)
                    .withSelection(Groups.SOURCE_ID + "=?", new String[] { sourceID })
                    .withValue(Groups.TITLE, sourceID).withValue(Groups.GROUP_VISIBLE, 1).build());
            super.commit();
        }
    } catch (RemoteException e) {
        throw new LocalStorageException("Couldn't update group names", e);
    }
}

From source file:nuclei.persistence.Query.java

public ContentProviderOperation toUpdateOperation(T object, QueryArgs args) {
    if (opType != QUERY_OPERATION_UPDATE)
        throw new IllegalArgumentException("Not an update query");
    if (contentValuesMapper == null)
        throw new IllegalArgumentException("Content Values Mapper is null");
    args.validate(this);
    return ContentProviderOperation.newUpdate(uri.toUri()).withSelection(selection, args.args())
            .withValues(contentValuesMapper.map(object)).build();
}

From source file:com.asalfo.wiulgi.util.Utils.java

private static ContentProviderOperation buildUpdateBatchOperation(String column, String value,
        String mongo_id) {/*from w ww.  jav a2 s .  c o  m*/

    Uri dirUri = WiulgiContract.Items.buildDirUri();
    ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(dirUri);

    builder.withValue(column, value);
    String selection = WiulgiContract.Items.MONGO_ID + "= ?";
    String[] selectionArgs = { mongo_id };
    builder.withSelection(selection, selectionArgs);

    return builder.build();
}

From source file:com.google.samples.apps.iosched.io.SessionsHandler.java

private void buildSession(boolean isInsert, Session session, ArrayList<ContentProviderOperation> list) {
    ContentProviderOperation.Builder builder;
    Uri allSessionsUri = ScheduleContractHelper
            .setUriAsCalledFromSyncAdapter(ScheduleContract.Sessions.CONTENT_URI);
    Uri thisSessionUri = ScheduleContractHelper
            .setUriAsCalledFromSyncAdapter(ScheduleContract.Sessions.buildSessionUri(session.id));

    if (isInsert) {
        builder = ContentProviderOperation.newInsert(allSessionsUri);
    } else {//from w w w  . j  av  a 2  s .c  om
        builder = ContentProviderOperation.newUpdate(thisSessionUri);
    }

    String speakerNames = "";
    if (mSpeakerMap != null) {
        // build human-readable list of speakers
        mStringBuilder.setLength(0);
        if (session.speakers != null) {
            for (int i = 0; i < session.speakers.length; ++i) {
                if (mSpeakerMap.containsKey(session.speakers[i])) {
                    mStringBuilder.append(i == 0 ? "" : i == session.speakers.length - 1 ? " and " : ", ")
                            .append(mSpeakerMap.get(session.speakers[i]).name.trim());
                } else {
                    LOGW(TAG, "Unknown speaker ID " + session.speakers[i] + " in session " + session.id);
                }
            }
        }
        speakerNames = mStringBuilder.toString();
    } else {
        LOGE(TAG, "Can't build speaker names -- speaker map is null.");
    }

    int color = mDefaultSessionColor;
    try {
        if (!TextUtils.isEmpty(session.color)) {
            color = Color.parseColor(session.color);
        }
    } catch (IllegalArgumentException ex) {
        LOGD(TAG, "Ignoring invalid formatted session color: " + session.color);
    }

    builder.withValue(ScheduleContract.SyncColumns.UPDATED, System.currentTimeMillis())
            .withValue(ScheduleContract.Sessions.SESSION_ID, session.id)
            .withValue(ScheduleContract.Sessions.SESSION_LEVEL, null) // Not available
            .withValue(ScheduleContract.Sessions.SESSION_TITLE, session.title)
            .withValue(ScheduleContract.Sessions.SESSION_ABSTRACT, session.description)
            .withValue(ScheduleContract.Sessions.SESSION_HASHTAG, session.hashtag)
            .withValue(ScheduleContract.Sessions.SESSION_START,
                    TimeUtils.timestampToMillis(session.startTimestamp, 0))
            .withValue(ScheduleContract.Sessions.SESSION_END,
                    TimeUtils.timestampToMillis(session.endTimestamp, 0))
            .withValue(ScheduleContract.Sessions.SESSION_TAGS, session.makeTagsList())
            // Note: we store this comma-separated list of tags IN ADDITION
            // to storing the tags in proper relational format (in the sessions_tags
            // relationship table). This is because when querying for sessions,
            // we don't want to incur the performance penalty of having to do a
            // subquery for every record to figure out the list of tags of each session.
            .withValue(ScheduleContract.Sessions.SESSION_SPEAKER_NAMES, speakerNames)
            // Note: we store the human-readable list of speakers (which is redundant
            // with the sessions_speakers relationship table) so that we can
            // display it easily in lists without having to make an additional DB query
            // (or another join) for each record.
            .withValue(ScheduleContract.Sessions.SESSION_KEYWORDS, null) // Not available
            .withValue(ScheduleContract.Sessions.SESSION_URL, session.url)
            .withValue(ScheduleContract.Sessions.SESSION_LIVESTREAM_ID,
                    session.isLivestream ? session.youtubeUrl : null)
            .withValue(ScheduleContract.Sessions.SESSION_MODERATOR_URL, null) // Not available
            .withValue(ScheduleContract.Sessions.SESSION_REQUIREMENTS, null) // Not available
            .withValue(ScheduleContract.Sessions.SESSION_YOUTUBE_URL,
                    session.isLivestream ? null : session.youtubeUrl)
            .withValue(ScheduleContract.Sessions.SESSION_PDF_URL, null) // Not available
            .withValue(ScheduleContract.Sessions.SESSION_NOTES_URL, null) // Not available
            .withValue(ScheduleContract.Sessions.ROOM_ID, session.room)
            .withValue(ScheduleContract.Sessions.SESSION_GROUPING_ORDER, session.groupingOrder)
            .withValue(ScheduleContract.Sessions.SESSION_IMPORT_HASHCODE, session.getImportHashCode())
            .withValue(ScheduleContract.Sessions.SESSION_MAIN_TAG, session.mainTag)
            .withValue(ScheduleContract.Sessions.SESSION_CAPTIONS_URL, session.captionsUrl)
            .withValue(ScheduleContract.Sessions.SESSION_PHOTO_URL, session.photoUrl)
            // Disabled since this isn't being used by this app.
            // .withValue(ScheduleContract.Sessions.SESSION_RELATED_CONTENT, session.relatedContent)
            .withValue(ScheduleContract.Sessions.SESSION_COLOR, color);
    list.add(builder.build());
}

From source file:com.germainz.identiconizer.services.IdenticonRemovalService.java

private void removeIdenticon(long id) {
    ContentValues values = new ContentValues();
    values.put(ContactsContract.Data.DATA15, (byte[]) null);
    final String selection = ContactsContract.Data._ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
    final String[] selectionArgs = new String[] { String.valueOf(id),
            ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE };
    mOps.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
            .withValue(ContactsContract.Data.DATA15, null).withSelection(selection, selectionArgs).build());
}

From source file:com.battlelancer.seriesguide.util.TraktTools.java

/**
 * Applies database ops in small increments for the given episodes, setting the appropriate
 * flag//from ww w  .  j  a v a 2s. co  m
 * in the given column.
 *
 * @param episodeFlagColumn  Which flag column the given data should change. Supports {@link
 *                           com.battlelancer.seriesguide.provider.SeriesGuideContract.Episodes#WATCHED}
 *                           and {@link com.battlelancer.seriesguide.provider.SeriesGuideContract.Episodes#COLLECTED}.
 * @param clearExistingFlags If set, existing flags for all of this shows episodes will be set
 *                           to the default flag prior applying other changes.
 */
public static void applyEpisodeFlagChanges(Context context, TvShow tvShow, String episodeFlagColumn,
        boolean clearExistingFlags) {
    if (tvShow.seasons == null) {
        return;
    }

    int episodeFlag;
    int episodeDefaultFlag;
    String clearSelection;
    switch (episodeFlagColumn) {
    case SeriesGuideContract.Episodes.WATCHED:
        episodeFlag = EpisodeFlags.WATCHED;
        episodeDefaultFlag = EpisodeFlags.UNWATCHED;
        // do not remove flag of skipped episodes, only for watched ones
        clearSelection = SeriesGuideContract.Episodes.WATCHED + "=" + EpisodeFlags.WATCHED;
        break;
    case SeriesGuideContract.Episodes.COLLECTED:
        episodeFlag = 1;
        episodeDefaultFlag = 0;
        // only remove flags for already collected episodes
        clearSelection = SeriesGuideContract.Episodes.COLLECTED + "=1";
        break;
    default:
        return;
    }

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

    if (clearExistingFlags) {
        // remove all flags for episodes of this show
        // loop below will run at least once (would not be here if not at least one season),
        // so op-apply is ensured
        batch.add(ContentProviderOperation
                .newUpdate(SeriesGuideContract.Episodes.buildEpisodesOfShowUri(tvShow.tvdb_id))
                .withSelection(clearSelection, null).withValue(episodeFlagColumn, episodeDefaultFlag).build());
    }

    for (TvShowSeason season : tvShow.seasons) {
        if (season == null || season.season == null || season.episodes == null
                || season.episodes.numbers == null) {
            continue;
        }

        // build db ops to flag episodes according to given data
        for (Integer episode : season.episodes.numbers) {
            batch.add(ContentProviderOperation
                    .newUpdate(SeriesGuideContract.Episodes.buildEpisodesOfShowUri(tvShow.tvdb_id))
                    .withSelection(SeriesGuideContract.Episodes.SEASON + "=" + season.season + " AND "
                            + SeriesGuideContract.Episodes.NUMBER + "=" + episode, null)
                    .withValue(episodeFlagColumn, episodeFlag).build());
        }

        // apply batch of this season
        try {
            DBUtils.applyInSmallBatches(context, batch);
        } catch (OperationApplicationException e) {
            Timber.e("Applying flag changes failed: " + tvShow.tvdb_id + " season: " + season.season
                    + " column: " + episodeFlagColumn, e);
            // do not abort, try other seasons
            // some episodes might be in incorrect state, but next update should fix that
            // this includes the clear flags op failing
        }
        batch.clear();
    }
}

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  ww w .ja  va  2s  .  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:org.c99.SyncProviderDemo.ContactsSyncAdapterService.java

private static void updateContactPhoto(ArrayList<ContentProviderOperation> operationList, long rawContactId,
        byte[] photo) {
    ContentProviderOperation.Builder builder = ContentProviderOperation
            .newDelete(ContactsContract.Data.CONTENT_URI);
    builder.withSelection(ContactsContract.Data.RAW_CONTACT_ID + " = '" + rawContactId + "' AND "
            + ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
            + "'", null);
    operationList.add(builder.build());/*from   w w w  .  j  a va 2 s  . com*/

    try {
        if (photo != null) {
            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, photo);
            operationList.add(builder.build());

            builder = ContentProviderOperation.newUpdate(RawContacts.CONTENT_URI);
            builder.withSelection(RawContacts.CONTACT_ID + " = '" + rawContactId + "'", null);
            builder.withValue(PhotoTimestampColumn, String.valueOf(System.currentTimeMillis()));
            operationList.add(builder.build());
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}