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.pixmob.droidlink.sync.SyncAdapter.java

private void doPerformSync(NetworkClient client, SharedPreferences prefs, ContentProviderClient provider,
        SyncResult syncResult, boolean fullSync) {
    // Prepare the query.
    final String selection = DEVICE_ID + "=? AND " + STATE + "=? OR " + STATE + "=?";
    final String[] selectionArgs = { client.getDeviceId(), String.valueOf(EventsContract.PENDING_UPLOAD_STATE),
            String.valueOf(EventsContract.PENDING_DELETE_STATE) };

    // Get local data to sync.
    final Map<String, JSONObject> eventsToUpload = new HashMap<String, JSONObject>(8);
    final Set<String> eventsToDelete = new HashSet<String>(4);
    Cursor c = null;/*from  w  w  w  . ja v  a 2  s.c  o  m*/
    try {
        c = provider.query(EventsContract.CONTENT_URI, PROJECTION, selection, selectionArgs, null);

        final int idIdx = c.getColumnIndexOrThrow(_ID);
        final int typeIdx = c.getColumnIndexOrThrow(TYPE);
        final int createdIdx = c.getColumnIndexOrThrow(CREATED);
        final int numberIdx = c.getColumnIndexOrThrow(NUMBER);
        final int nameIdx = c.getColumnIndexOrThrow(NAME);
        final int messageIdx = c.getColumnIndexOrThrow(MESSAGE);
        final int stateIdx = c.getColumnIndexOrThrow(STATE);

        while (c.moveToNext()) {
            final String eventId = c.getString(idIdx);
            final int eventState = c.getInt(stateIdx);

            if (EventsContract.PENDING_UPLOAD_STATE == eventState) {
                // This is a newly created event.
                final JSONObject event = new JSONObject();
                try {
                    event.put("deviceId", client.getDeviceId());
                    event.put("created", c.getLong(createdIdx));
                    event.put("type", c.getInt(typeIdx));
                    event.put("number", c.getString(numberIdx));
                    event.put("name", c.getString(nameIdx));
                    event.put("message", c.getString(messageIdx));
                } catch (JSONException e) {
                    Log.w(TAG, "Invalid event " + eventId + ": cannot sync", e);
                    syncResult.stats.numSkippedEntries++;
                    continue;
                }
                eventsToUpload.put(eventId, event);
            } else if (EventsContract.PENDING_DELETE_STATE == eventState) {
                // The user wants this event to be deleted.
                eventsToDelete.add(eventId);
            }
        }
    } catch (RemoteException e) {
        Log.e(TAG, "Failed to get events: cannot sync", e);
        syncResult.stats.numIoExceptions++;
    } finally {
        if (c != null) {
            c.close();
            c = null;
        }
    }

    final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(32);
    final ContentValues values = new ContentValues(8);

    if (eventsToDelete.isEmpty()) {
        Log.i(TAG, "No events to delete");
    } else {
        Log.i(TAG, "Found " + eventsToDelete.size() + " event(s) to delete");
    }

    // Delete events on the remote server.
    for (final String eventId : eventsToDelete) {
        if (DEVELOPER_MODE) {
            Log.d(TAG, "Deleting event: " + eventId);
        }

        try {
            client.delete("/events/" + eventId);

            if (DEVELOPER_MODE) {
                Log.d(TAG, "Deleting event in local database: " + eventId);
            }
            batch.add(ContentProviderOperation
                    .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build());
            syncResult.stats.numDeletes++;
        } catch (IOException e) {
            Log.e(TAG, "Event deletion error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }
    }

    try {
        provider.applyBatch(batch);
    } catch (Exception e) {
        Log.w(TAG, "Database error: cannot sync", e);
        syncResult.stats.numIoExceptions++;
        return;
    }
    batch.clear();

    if (fullSync) {
        // Get all events from the remote server.
        final JSONArray events;
        if (DEVELOPER_MODE) {
            Log.d(TAG, "Fetching events from the remote server");
        }
        try {
            events = client.getAsArray("/events");
        } catch (IOException e) {
            Log.e(TAG, "Event listing error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }

        final int eventsLen = events != null ? events.length() : 0;
        if (eventsLen == 0) {
            Log.i(TAG, "No events from the remote server");
        } else {
            Log.i(TAG, "Found " + eventsLen + " event(s) from the remote server");
        }

        // Build a collection with local event identifiers.
        // This collection will be used to identify which events have
        // been deleted on the remote server.
        final Set<String> localEventIds;
        try {
            c = provider.query(EventsContract.CONTENT_URI, PROJECTION_ID, STATE + "=?",
                    new String[] { String.valueOf(EventsContract.UPLOADED_STATE) }, null);
            localEventIds = new HashSet<String>(c.getCount());

            final int idIdx = c.getColumnIndexOrThrow(_ID);
            while (c.moveToNext()) {
                final String eventId = c.getString(idIdx);
                localEventIds.add(eventId);
            }
        } catch (RemoteException e) {
            Log.e(TAG, "Failed to get events from local database", e);
            syncResult.stats.numIoExceptions++;
            return;
        } finally {
            if (c != null) {
                c.close();
                c = null;
            }
        }

        String newEventId = null;
        int newEventCount = 0;

        // Reconcile remote events with local events.
        for (int i = 0; i < eventsLen; ++i) {
            String eventId = null;
            try {
                final JSONObject event = events.getJSONObject(i);
                eventId = event.getString("id");

                // Check if this event exists in the local database.
                if (localEventIds.contains(eventId)) {
                    // Found the event: update it.
                    values.clear();
                    values.put(NUMBER, trimToNull(event.getString("number")));
                    values.put(NAME, trimToNull(event.getString("name")));
                    values.put(MESSAGE, trimToNull(event.getString("message")));

                    if (DEVELOPER_MODE) {
                        Log.d(TAG, "Updating event in local database: " + eventId);
                    }
                    batch.add(ContentProviderOperation
                            .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId))
                            .withExpectedCount(1).withValues(values).build());
                    syncResult.stats.numUpdates++;
                } else {
                    // The event was not found: insert it.
                    values.clear();
                    values.put(_ID, eventId);
                    values.put(DEVICE_ID, event.getString("deviceId"));
                    values.put(CREATED, event.getLong("created"));
                    values.put(TYPE, event.getInt("type"));
                    values.put(NUMBER, trimToNull(event.getString("number")));
                    values.put(NAME, trimToNull(event.getString("name")));
                    values.put(MESSAGE, trimToNull(event.getString("message")));
                    values.put(STATE, EventsContract.UPLOADED_STATE);

                    if (DEVELOPER_MODE) {
                        Log.d(TAG, "Adding event to local database: " + eventId);
                    }
                    batch.add(ContentProviderOperation
                            .newInsert(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId))
                            .withValues(values).build());
                    syncResult.stats.numInserts++;

                    ++newEventCount;
                    if (newEventId == null) {
                        newEventId = eventId;
                    }
                }

                // This event now exists in the local database:
                // remove its identifier from this collection as we
                // don't want to delete it.
                localEventIds.remove(eventId);
            } catch (JSONException e) {
                Log.w(TAG, "Invalid event at index " + i + ": cannot sync", e);
                syncResult.stats.numSkippedEntries++;
                continue;
            }
        }

        // The remaining event identifiers was removed on the remote
        // server: there are still present in the local database. These
        // events are now being deleted.
        for (final String eventId : localEventIds) {
            if (DEVELOPER_MODE) {
                Log.d(TAG, "Deleting event in local database: " + eventId);
            }
            batch.add(ContentProviderOperation
                    .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build());
            syncResult.stats.numDeletes++;
        }

        try {
            provider.applyBatch(batch);
        } catch (Exception e) {
            Log.e(TAG, "Database error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        }
        batch.clear();

        if (newEventCount > 1) {
            newEventId = null;
        }
        if (newEventCount != 0) {
            startSyncNotificationService(newEventCount, newEventId);
        }
    }

    final int numEventsToUpload = eventsToUpload.size();
    if (numEventsToUpload == 0) {
        Log.i(TAG, "No events to upload");
    } else {
        Log.i(TAG, "Found " + numEventsToUpload + " event(s) to upload");
    }

    // Send local events to the remote server.
    for (final Map.Entry<String, JSONObject> entry : eventsToUpload.entrySet()) {
        final String eventId = entry.getKey();

        if (DEVELOPER_MODE) {
            Log.d(TAG, "Uploading event: " + eventId);
        }

        final JSONObject event = entry.getValue();
        try {
            client.put("/events/" + eventId, event);

            if (DEVELOPER_MODE) {
                Log.d(TAG, "Updating event state to UPLOADED: " + eventId);
            }
            values.clear();
            values.put(STATE, EventsContract.UPLOADED_STATE);
            batch.add(ContentProviderOperation
                    .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).withValues(values)
                    .withExpectedCount(1).build());
            syncResult.stats.numUpdates++;

            Log.i(TAG, "Event upload successful: " + eventId);
        } catch (NetworkClientException e) {
            if (e.getStatusCode() == 404) {
                Log.e(TAG, "Device not found: cannot sync", e);
                registerDevice();
            } else {
                Log.e(TAG, "Network error: cannot sync", e);
            }
            syncResult.stats.numIoExceptions++;
            return;
        } catch (IOException e) {
            Log.e(TAG, "Event upload error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }
    }

    try {
        provider.applyBatch(batch);
    } catch (Exception e) {
        Log.w(TAG, "Database error: cannot sync", e);
        syncResult.stats.numIoExceptions++;
        return;
    }
    batch.clear();

    final SharedPreferences.Editor prefsEditor = prefs.edit();
    final boolean syncRequired = !eventsToDelete.isEmpty() || !eventsToUpload.isEmpty();
    if (syncRequired) {
        // Generate an unique sync token: the server will send this token to
        // every devices. If this token is received on this device, the sync
        // will not start.
        final String syncToken = UUID.randomUUID().toString();
        prefsEditor.putString(SP_KEY_SYNC_TOKEN, syncToken);
        Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor);

        // Sync user devices.
        try {
            final JSONObject data = new JSONObject();
            data.put("token", syncToken);
            client.post("/devices/" + client.getDeviceId() + "/sync", data);
        } catch (NetworkClientException e) {
            if (e.getStatusCode() == 404) {
                registerDevice();
            }
        } catch (IOException e) {
            Log.e(TAG, "Device sync error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        } catch (JSONException e) {
            Log.w(TAG, "Invalid sync token " + syncToken + ": cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        }
    }

    // Store sync time.
    prefsEditor.putLong(SP_KEY_LAST_SYNC, System.currentTimeMillis());
    Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor);
}

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

private void addMovieOps(@NonNull MovieDetails movieDetails, long movieRowId,
        @NonNull ArrayList<ContentProviderOperation> ops) {
    ops.add(ContentProviderOperation.newUpdate(MovieContract.Movie.buildMovieUri(movieRowId))
            .withValues(movieDetails.getContentValuesEntry()).build());
}

From source file:com.owncloud.android.datamodel.FileDataStorageManager.java

/**
 * Inserts or updates the list of files contained in a given folder.
 * <p/>/*ww w. j  av  a  2s  .  c o m*/
 * CALLER IS THE RESPONSIBLE FOR GRANTING RIGHT UPDATE OF INFORMATION, NOT THIS METHOD.
 * HERE ONLY DATA CONSISTENCY SHOULD BE GRANTED
 *
 * @param folder
 * @param updatedFiles
 * @param filesToRemove
 */
public void saveFolder(OCFile folder, Collection<OCFile> updatedFiles, Collection<OCFile> filesToRemove) {

    Log_OC.d(TAG, "Saving folder " + folder.getRemotePath() + " with " + updatedFiles.size() + " children and "
            + filesToRemove.size() + " files to remove");

    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(
            updatedFiles.size());

    // prepare operations to insert or update files to save in the given folder
    for (OCFile file : updatedFiles) {
        ContentValues cv = new ContentValues();
        cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
        cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
                file.getModificationTimestampAtLastSyncForData());
        cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
        cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
        cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
        cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
        cv.put(ProviderTableMeta.FILE_PARENT, folder.getFileId());
        cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
        if (!file.isFolder()) {
            cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
        }
        cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
        cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
        cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
        cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
        cv.put(ProviderTableMeta.FILE_TREE_ETAG, file.getTreeEtag());
        cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, file.isSharedViaLink() ? 1 : 0);
        cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, file.isSharedWithSharee() ? 1 : 0);
        cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
        cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
        cv.put(ProviderTableMeta.FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail());
        cv.put(ProviderTableMeta.FILE_IS_DOWNLOADING, file.isDownloading());
        cv.put(ProviderTableMeta.FILE_ETAG_IN_CONFLICT, file.getEtagInConflict());
        cv.put(ProviderTableMeta.FILE_PRIVATE_LINK, file.getPrivateLink());

        boolean existsByPath = fileExists(file.getRemotePath());
        if (existsByPath || fileExists(file.getFileId())) {
            // updating an existing file
            operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).withValues(cv)
                    .withSelection(ProviderTableMeta._ID + "=?",
                            new String[] { String.valueOf(file.getFileId()) })
                    .build());

        } else {
            // adding a new file
            setInitialAvailableOfflineStatus(file, cv);
            operations.add(
                    ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).withValues(cv).build());
        }
    }

    // prepare operations to remove files in the given folder
    String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta.FILE_PATH + "=?";
    String[] whereArgs = null;
    for (OCFile file : filesToRemove) {
        if (file.getParentId() == folder.getFileId()) {
            whereArgs = new String[] { mAccount.name, file.getRemotePath() };
            if (file.isFolder()) {
                operations.add(ContentProviderOperation
                        .newDelete(
                                ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, file.getFileId()))
                        .withSelection(where, whereArgs).build());

                File localFolder = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
                if (localFolder.exists()) {
                    removeLocalFolder(localFolder);
                }
            } else {
                operations.add(ContentProviderOperation.newDelete(
                        ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, file.getFileId()))
                        .withSelection(where, whereArgs).build());

                if (file.isDown()) {
                    String path = file.getStoragePath();
                    new File(path).delete();
                    triggerMediaScan(path); // notify MediaScanner about removed file
                }
            }
        }
    }

    // update metadata of folder
    ContentValues cv = new ContentValues();
    cv.put(ProviderTableMeta.FILE_MODIFIED, folder.getModificationTimestamp());
    cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
            folder.getModificationTimestampAtLastSyncForData());
    cv.put(ProviderTableMeta.FILE_CREATION, folder.getCreationTimestamp());
    cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, folder.getFileLength());
    cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, folder.getMimetype());
    cv.put(ProviderTableMeta.FILE_NAME, folder.getFileName());
    cv.put(ProviderTableMeta.FILE_PARENT, folder.getParentId());
    cv.put(ProviderTableMeta.FILE_PATH, folder.getRemotePath());
    cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
    cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, folder.getLastSyncDateForProperties());
    cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, folder.getLastSyncDateForData());
    cv.put(ProviderTableMeta.FILE_ETAG, folder.getEtag());
    cv.put(ProviderTableMeta.FILE_TREE_ETAG, folder.getTreeEtag());
    cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, folder.isSharedViaLink() ? 1 : 0);
    cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, folder.isSharedWithSharee() ? 1 : 0);
    cv.put(ProviderTableMeta.FILE_PERMISSIONS, folder.getPermissions());
    cv.put(ProviderTableMeta.FILE_REMOTE_ID, folder.getRemoteId());
    cv.put(ProviderTableMeta.FILE_PRIVATE_LINK, folder.getPrivateLink());

    operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).withValues(cv)
            .withSelection(ProviderTableMeta._ID + "=?", new String[] { String.valueOf(folder.getFileId()) })
            .build());

    // apply operations in batch
    ContentProviderResult[] results = null;
    Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
    try {
        if (getContentResolver() != null) {
            results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);

        } else {
            results = getContentProviderClient().applyBatch(operations);
        }

    } catch (OperationApplicationException e) {
        Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());

    } catch (RemoteException e) {
        Log_OC.e(TAG, "Exception in batch of operations  " + e.getMessage());
    }

    // update new id in file objects for insertions
    if (results != null) {
        long newId;
        Iterator<OCFile> filesIt = updatedFiles.iterator();
        OCFile file = null;
        for (int i = 0; i < results.length; i++) {
            if (filesIt.hasNext()) {
                file = filesIt.next();
            } else {
                file = null;
            }
            if (results[i].uri != null) {
                newId = Long.parseLong(results[i].uri.getPathSegments().get(1));
                //updatedFiles.get(i).setFileId(newId);
                if (file != null) {
                    file.setFileId(newId);
                }
            }
        }
    }

}

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

/** Enqueues removing the dirty flag from a locally-stored resource. Requires commit() to be effective! */
public void clearDirty(Resource resource) {
    pendingOperations.add(//from  ww  w.j  a v  a 2s .  com
            ContentProviderOperation.newUpdate(ContentUris.withAppendedId(entriesURI(), resource.getLocalID()))
                    .withValue(entryColumnDirty(), 0).build());
}

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  va  2 s  .  com*/
    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:org.dmfs.tasks.SettingsListFragment.java

/**
 * This function is called to save the any modifications made to the displayed list. It retrieves the {@link HashMap} from the adapter of the list and uses
 * it makes the changes persistent. For this it uses a batch operation provided by {@link ContentResolver}. The operations to be performed in the batch
 * operation are stored in an {@link ArrayList} of {@link ContentProviderOperation}.
 * /*from w w  w  .  j  a  va  2 s.c  o m*/
 * @return <code>true</code> if the save operation was successful, <code>false</code> otherwise.
 */
public boolean saveListState() {
    HashMap<Long, Boolean> savedPositions = ((VisibleListAdapter) getListAdapter()).getState();
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    for (Long posInt : savedPositions.keySet()) {
        boolean val = savedPositions.get(posInt);
        ContentProviderOperation op = ContentProviderOperation
                .newUpdate(TaskContract.TaskLists.getContentUri(mAuthority))
                .withSelection(TaskContract.TaskLists._ID + "=?", new String[] { posInt.toString() })
                .withValue(mListCompareColumnName, val ? "1" : "0").build();
        ops.add(op);
    }

    try {
        mContext.getContentResolver().applyBatch(mAuthority, ops);
    } catch (RemoteException e) {
        e.printStackTrace();
        return false;
    } catch (OperationApplicationException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

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;/*  ww w .  j  av  a 2 s . co 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);
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

public static void addAggregateException(Context context, Account account, RawContact rawContact,
        BatchOperation batchOperation) {
    final long rawContactId = lookupRawContact(context.getContentResolver(), account, rawContact.getUid());

    if (rawContactId <= 0) {
        return;// www. ja  va 2s . c  o m
    }

    ContentProviderOperation.Builder builder;
    builder = ContentProviderOperation.newUpdate(ContactsContract.AggregationExceptions.CONTENT_URI)
            .withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID1,
                    Long.toString(rawContact.getJoinContactId()))
            .withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID2, Long.toString(rawContactId))
            .withValue(ContactsContract.AggregationExceptions.TYPE,
                    ContactsContract.AggregationExceptions.TYPE_KEEP_TOGETHER);

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

From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java

/**
 * We know that the group exists locally, so we can use the data in the JSON group as gold
 * @param group//from   ww  w .ja  v a2 s .co m
 * @param provider
 * @param authToken
 * @param account
 * @param syncResult
 * @throws JSONException
 * @throws RemoteException
 * @throws OperationApplicationException
 */
private void optimisticallyAddContactsToExistingGroup(JSONObject group, ContentProviderClient provider,
        String authToken, Account account, SyncResult syncResult) throws JSONException, RemoteException {

    if (!group.has(JSONKeys.KEY_MEMBERS)) {
        return;
    }
    String groupCloudId = group.getString(JSONKeys.KEY_ID);
    Cursor groupCursor = provider.query(GMSGroups.CONTENT_URI, new String[] { GMSGroup._ID, GMSGroup.CLOUD_ID },
            GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }, null);
    try {
        if (groupCursor == null || 1 != groupCursor.getCount() || !groupCursor.moveToFirst()) {
            syncResult.databaseError = true;
            return;
        }
        long groupId = groupCursor.getLong(0);
        if (groupId < 0L) {
            syncResult.databaseError = true;
            return;
        }
        // Optimistically add the contacts
        JSONArray membersArray = group.getJSONArray(JSONKeys.KEY_MEMBERS);
        for (int j = 0; j < membersArray.length(); ++j) {
            JSONObject member = membersArray.getJSONObject(j);
            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            // If the first operation asserts it means the contact exists already
            // Operation 0
            ContentProviderOperation op = ContentProviderOperation.newAssertQuery(GMSContacts.CONTENT_URI)
                    .withSelection(GMSContact.CLOUD_ID + "=? AND " + GMSContact.GROUP_ID + "=?",
                            new String[] { member.getString(JSONKeys.KEY_ID), String.valueOf(groupId) })
                    .withExpectedCount(0).build();
            ops.add(op);
            op = ContentProviderOperation.newInsert(GMSContacts.CONTENT_URI)
                    .withValues(GMSApplication.getMemberValues(member)).withValue(GMSContact.GROUP_ID, groupId)
                    .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).build();
            ops.add(op);
            try {
                @SuppressWarnings("unused")
                ContentProviderResult[] results = provider.applyBatch(ops);
            } catch (OperationApplicationException e) {
                // The contact already exists, so we'll optionally update it, based on its version
                Cursor contactCursor = null;
                try {
                    contactCursor = provider.query(GMSContacts.CONTENT_URI,
                            new String[] { GMSContact._ID, GMSContact.CLOUD_ID, GMSContact.GROUP_ID },
                            GMSContact.CLOUD_ID + "=? AND " + GMSContact.GROUP_ID + "=?",
                            new String[] { member.getString(JSONKeys.KEY_ID), String.valueOf(groupId) }, null);
                    if (contactCursor == null || !contactCursor.moveToFirst()) {
                        syncResult.databaseError = true;
                        return;
                    }
                    // The member already exists, so optinally update it
                    ops = new ArrayList<ContentProviderOperation>();
                    // 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(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withSelection(GMSContact.VERSION + "=?",
                                    new String[] { member.getString(JSONKeys.KEY_VERSION) })
                            .withExpectedCount(0).build();
                    ops.add(op);
                    op = ContentProviderOperation
                            .newUpdate(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withValues(GMSApplication.getMemberValues(member))
                            .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).withExpectedCount(1)
                            .build();
                    ops.add(op);
                    provider.applyBatch(ops);
                } catch (OperationApplicationException l) {
                    ops = new ArrayList<ContentProviderOperation>();
                    // Operation 0 - we know it exists and is of the current version, so no update of attributes is needed
                    // We still have to update the status to SYNCED so we don't blow it away later.
                    op = ContentProviderOperation
                            .newUpdate(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).withExpectedCount(1)
                            .build();
                    ops.add(op);
                    try {
                        provider.applyBatch(ops);
                    } catch (OperationApplicationException e1) {
                        syncResult.stats.numSkippedEntries++;
                        e1.printStackTrace();
                    }
                } finally {
                    if (contactCursor != null) {
                        contactCursor.close();
                    }
                }
            }
        }
    } finally {
        if (groupCursor != null) {
            groupCursor.close();
        }
    }
}