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:com.forktech.cmerge.ui.ContactsListFragment.java

private void mergeContacts() {
    ArrayList<Integer> list = (ArrayList<Integer>) getContacts();
    int numOfContacts = list.size();

    if (numOfContacts < 2) {
        Toast.makeText(getActivity(), "Atleast select two contacts to merge", Toast.LENGTH_SHORT).show();
        return;/*from w  w  w.j a v a 2  s . c  o m*/
    }
    mAdapter.clearChecks(true);
    for (int i = 0; i < numOfContacts - 1; i++) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        ops.add(ContentProviderOperation.newUpdate(ContactsContract.AggregationExceptions.CONTENT_URI)
                .withValue(ContactsContract.AggregationExceptions.TYPE,
                        ContactsContract.AggregationExceptions.TYPE_KEEP_TOGETHER)
                .withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID1, getContacts().get(0))
                .withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID2, getContacts().get(i + 1))
                .build());
        // Log.e("", Arrays.deepToString(getContacts().toArray()));

        try {
            ContentProviderResult[] result = getActivity().getContentResolver()
                    .applyBatch(ContactsContract.AUTHORITY, ops);
            Log.e("",
                    "result length : " + result.length + " :: " + result[0].uri + result[0].describeContents());
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.linphone.ContactEditorFragment.java

private void setContactPhoto() {
    ContentResolver cr = getActivity().getContentResolver();
    Uri updateUri = ContactsContract.Data.CONTENT_URI;

    if (photoToAdd != null) {
        //New contact
        if (isNewContact) {
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, contactID)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photoToAdd).build());
        } else { //update contact picture
            String w = ContactsContract.Data.CONTACT_ID + "='" + contact.getID() + "' AND "
                    + ContactsContract.Data.MIMETYPE + " = '"
                    + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";

            Cursor queryCursor = cr.query(updateUri, new String[] { ContactsContract.Data._ID }, w, null, null);
            if (queryCursor == null) {
                try {
                    throw new SyncFailedException("EE");
                } catch (SyncFailedException e) {
                    e.printStackTrace();
                }//from  ww  w  .j  a  va2 s .  c o  m
            } else {
                if (contact.getPhoto() == null) {
                    String rawContactId = ContactsManager.getInstance().findRawContactID(cr,
                            String.valueOf(contactID));
                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValue(ContactsContract.Data.RAW_CONTACT_ID, rawContactId)
                            .withValue(ContactsContract.Data.MIMETYPE,
                                    ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photoToAdd).build());
                }

                if (queryCursor.moveToFirst()) { // otherwise no photo
                    int colIdx = queryCursor.getColumnIndex(ContactsContract.Data._ID);
                    long id = queryCursor.getLong(colIdx);

                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(ContactsContract.Data._ID + "= ?",
                                    new String[] { String.valueOf(id) })
                            .withValue(ContactsContract.Data.MIMETYPE,
                                    ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photoToAdd).build());
                }
                queryCursor.close();
            }
        }
    }
}

From source file:org.totschnig.myexpenses.sync.SyncAdapter.java

@VisibleForTesting
public void collectOperations(@NonNull TransactionChange change, long accountId,
        ArrayList<ContentProviderOperation> ops, int parentOffset) {
    Uri uri = Transaction.CALLER_IS_SYNC_ADAPTER_URI;
    switch (change.type()) {
    case created:
        ops.addAll(getContentProviderOperationsForCreate(change, ops.size(), parentOffset));
        break;/*w  w w . j a v  a2s  .  com*/
    case updated:
        ContentValues values = toContentValues(change);
        if (values.size() > 0) {
            ops.add(ContentProviderOperation.newUpdate(uri)
                    .withSelection(KEY_UUID + " = ? AND " + KEY_ACCOUNTID + " = ?",
                            new String[] { change.uuid(), String.valueOf(accountId) })
                    .withValues(values).build());
        }
        break;
    case deleted:
        ops.add(ContentProviderOperation.newDelete(uri)
                .withSelection(KEY_UUID + " = ?", new String[] { change.uuid() }).build());
        break;
    }
    if (change.splitParts() != null) {
        final int newParentOffset = ops.size() - 1;
        List<TransactionChange> splitPartsFiltered = filterDeleted(change.splitParts(),
                findDeletedUuids(Stream.of(change.splitParts())));
        Stream.of(splitPartsFiltered).forEach(splitChange -> collectOperations(splitChange, accountId, ops,
                change.isCreate() ? newParentOffset : -1)); //back reference is only used when we insert a new split, for updating an existing split we search for its _id via its uuid
    }
}

From source file:org.totschnig.myexpenses.model.Account.java

private ContentProviderOperation updateTransferPeersForTransactionDelete(String rowSelect,
        String[] selectionArgs) {
    ContentValues args = new ContentValues();
    args.put(KEY_COMMENT, MyApplication.getInstance().getString(R.string.peer_transaction_deleted, label));
    args.putNull(KEY_TRANSFER_ACCOUNT);// ww w .j  a va 2s .  co m
    args.putNull(KEY_TRANSFER_PEER);
    return ContentProviderOperation.newUpdate(Transaction.CONTENT_URI).withValues(args)
            .withSelection(KEY_TRANSFER_PEER + " IN (" + rowSelect + ")", selectionArgs).build();
}

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

private void deleteUnsyncedItems(ContentProviderClient provider, Account account, SyncResult syncResult)
        throws RemoteException, JSONException {

    Log.d(TAG, "Delete unsynced items before count: " + syncResult.stats.numDeletes);
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ContentProviderOperation op;/*from w w w .j a  v a  2  s  .  c  o m*/
    ContentProviderResult[] results;

    // This is the good part
    Cursor unsyncedGroupsCursor = null;
    try {
        final String SELECT = GMSGroup.STATUS + " ISNULL OR " + GMSGroup.STATUS + " != "
                + GMSGroup.STATUS_SYNCED;
        unsyncedGroupsCursor = provider.query(GMSGroups.CONTENT_URI, new String[] { GMSGroup._ID,
                GMSGroup.CLOUD_ID, GMSGroup.STATUS, GMSGroup.NAME, GMSGroup.RAW_CONTACT_ID }, SELECT, null,
                null);
        ContentProviderClient contactsProvider;
        if (unsyncedGroupsCursor.moveToFirst()) {
            contactsProvider = getContext().getContentResolver()
                    .acquireContentProviderClient(ContactsContract.AUTHORITY);
            do {
                long groupId = unsyncedGroupsCursor.getLong(0);
                long groupRawContactId = unsyncedGroupsCursor.getLong(4);
                Cursor memberCursor = null;
                try {
                    memberCursor = provider.query(GMSContacts.CONTENT_URI,
                            new String[] { GMSContact._ID, GMSContact.GROUP_ID }, GMSContact.GROUP_ID + "=?",
                            new String[] { String.valueOf(groupId) }, null);
                    while (memberCursor.moveToNext()) {
                        op = ContentProviderOperation.newDelete(
                                ContentUris.withAppendedId(GMSContacts.CONTENT_URI, memberCursor.getLong(0)))
                                .build();
                        ops.add(op);
                    }
                } finally {
                    if (memberCursor != null) {
                        memberCursor.close();
                    }
                }
                op = ContentProviderOperation
                        .newDelete(ContentUris.withAppendedId(GMSGroups.CONTENT_URI, groupId)).build();
                ops.add(op);
                if (groupRawContactId <= 0) {
                    Cursor accountContactsCursor = null;
                    try {
                        String sourceId = unsyncedGroupsCursor.getString(1);
                        Log.d(TAG, String.format("Unsynced Group Id: %1$d, SourceId: %2$s", groupId, sourceId));
                        accountContactsCursor = GMSContactOperations.findGroupInContacts(contactsProvider,
                                account, sourceId);
                        if (accountContactsCursor != null && accountContactsCursor.moveToFirst()) {
                            groupRawContactId = accountContactsCursor.getLong(0);
                        }
                    } finally {
                        if (accountContactsCursor != null) {
                            accountContactsCursor.close();
                        }
                    }
                    GMSContactOperations.removeGroupFromContacts(contactsProvider, account, groupRawContactId,
                            syncResult);
                }
            } while (unsyncedGroupsCursor.moveToNext());
        }
    } finally {
        if (unsyncedGroupsCursor != null) {
            unsyncedGroupsCursor.close();
        }
    }
    // Now delete any unsynced contacts from the local provider
    op = ContentProviderOperation.newDelete(GMSContacts.CONTENT_URI)
            .withSelection(
                    GMSContact.STATUS + " ISNULL OR " + GMSContact.STATUS + " != " + GMSContact.STATUS_SYNCED,
                    null)
            .build();
    ops.add(op);

    op = ContentProviderOperation.newUpdate(GMSGroups.CONTENT_URI).withValue(GMSGroup.STATUS, null).build();
    ops.add(op);

    op = ContentProviderOperation.newUpdate(GMSContacts.CONTENT_URI).withValue(GMSContact.STATUS, null).build();
    ops.add(op);
    try {
        results = provider.applyBatch(ops);
        int numResults = results.length;
        for (int i = 0; i < numResults; ++i) {
            // The first first N-2 results were deletes
            if (i < numResults - 2) {
                syncResult.stats.numDeletes += results[i].count;
            } else {
                // The last two results were updates
                syncResult.stats.numEntries += results[i].count;
            }
        }
        Log.d(TAG, String.format("Delete unsynced items after count: %1$d, entries: %2$d",
                syncResult.stats.numDeletes, syncResult.stats.numEntries));
    } catch (OperationApplicationException e) {
        syncResult.stats.numSkippedEntries++;
        e.printStackTrace();
    }
}

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());/*from ww  w . jav a  2  s. c om*/
    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:at.bitfire.vcard4android.AndroidContact.java

public int update(Contact contact) throws ContactsStorageException {
    this.contact = contact;

    BatchOperation batch = new BatchOperation(addressBook.provider);

    ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(rawContactSyncURI());
    buildContact(builder, true);//  w  w w  .  ja v a2s . co m
    batch.enqueue(builder.build());

    // delete old data rows before adding the new ones
    Uri dataRowsUri = addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI);
    batch.enqueue(ContentProviderOperation.newDelete(dataRowsUri)
            .withSelection(RawContacts.Data.RAW_CONTACT_ID + "=?", new String[] { String.valueOf(id) })
            .build());
    insertDataRows(batch);
    int results = batch.commit();

    insertPhoto(contact.photo);

    return results;
}

From source file:com.chatwing.whitelabel.managers.ChatboxModeManager.java

@Subscribe
public void onCreateBookmarkEvent(CreateBookmarkEvent event) {
    if (handleCreateBookmarkException(event)) {
        return;/*from  w ww  .  j a  v  a  2s  . c o  m*/
    }
    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
    SyncedBookmark syncedBookmark = event.getResponse().getData();
    ChatBox chatBox = syncedBookmark.getChatBox();
    //Update local chatbox
    batch.add(ContentProviderOperation.newUpdate(ChatWingContentProvider.getChatBoxWithIdUri(chatBox.getId()))
            .withValues(ChatBoxTable.getContentValues(chatBox, null)).build());

    //Update local bookmarks
    int chatBoxId = chatBox.getId();
    syncedBookmark.setIsSynced(true);
    if (ChatWingContentProvider.hasSyncedBookmarkInDB(mActivityDelegate.getActivity().getContentResolver(),
            chatBoxId)) {
        //Update existing bookmark
        Uri syncedBookmarkWithChatBoxIdUri = ChatWingContentProvider
                .getSyncedBookmarkWithChatBoxIdUri(chatBoxId);
        batch.add(ContentProviderOperation.newUpdate(syncedBookmarkWithChatBoxIdUri)
                .withValues(SyncedBookmarkTable.getContentValues(syncedBookmark)).build());
    } else {
        //Somehow local bookmark is deleted, it should be add back
        Uri syncedBookmarksUri = ChatWingContentProvider.getSyncedBookmarksUri();
        batch.add(ContentProviderOperation.newInsert(syncedBookmarksUri)
                .withValues(SyncedBookmarkTable.getContentValues(syncedBookmark)).build());
    }

    try {
        mActivityDelegate.getActivity().getContentResolver().applyBatch(ChatWingContentProvider.AUTHORITY,
                batch);
    } catch (RemoteException e) {
        mActivityDelegate.handle(e, R.string.error_failed_to_save_bookmark);
    } catch (OperationApplicationException e) {
        mActivityDelegate.handle(e, R.string.error_failed_to_save_bookmark);
    }
}

From source file:com.ubuntuone.android.files.service.MetaService.java

/**
 * Given parents resource path and {@link ArrayList} of {@link NodeInfo}s of
 * its children, syncs cached info of these children. Updating children in
 * one method enables us to make use of database transaction.<br />
 * <ul>/*  w  w w . j ava2 s  .c o m*/
 * <li>- inserts if child is new</li>
 * <li>- updates if child has changed [thus marks is_cached = false]</li>
 * <li>- deletes if child is missing [dead node]</li>
 * </ul>
 * 
 * @param parentResourcePath
 *            the resource path of childrens parent
 * @param children
 *            {@link NodeInfo}s of the parents children
 * @throws OperationApplicationException 
 * @throws RemoteException 
 */
public void getDirectoryNode(final String resourcePath, final ResultReceiver receiver) {
    Log.i(TAG, "getDirectoryNode()");
    final String[] projection = new String[] { Nodes._ID, Nodes.NODE_RESOURCE_PATH, Nodes.NODE_GENERATION,
            Nodes.NODE_DATA };
    final String selection = Nodes.NODE_RESOURCE_PATH + "=?";

    final Set<Integer> childrenIds = MetaUtilities.getChildrenIds(resourcePath);

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

    final Bundle data = new Bundle();
    data.putString(EXTRA_RESOURCE_PATH, resourcePath);

    api.listDirectory(resourcePath, new U1NodeListener() {
        @Override
        public void onStart() {
            if (receiver != null)
                receiver.send(Status.RUNNING, data);
        }

        @Override
        public void onSuccess(U1Node node) {
            if (node.getKind() == U1NodeKind.FILE && ((U1File) node).getSize() == null) {
                // Ignore files with null size.
                return;
            }
            final String[] selectionArgs = new String[] { node.getResourcePath() };
            final Cursor c = contentResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs,
                    null);
            try {
                ContentValues values = Nodes.valuesFromRepr(node);
                if (c.moveToFirst()) {
                    final int id = c.getInt(c.getColumnIndex(Nodes._ID));
                    // Node is live.
                    childrenIds.remove(id);

                    // Update node.
                    final long generation = c.getLong(c.getColumnIndex(Nodes.NODE_GENERATION));
                    final long newGeneration = node.getGeneration();
                    if (generation < newGeneration) {
                        Log.v(TAG, "updating child node, new generation");
                        values.put(Nodes.NODE_IS_CACHED, false);
                        values.put(Nodes.NODE_DATA, "");

                        String data = c.getString(c.getColumnIndex(Nodes.NODE_DATA));
                        FileUtilities.removeSilently(data);

                        Uri uri = MetaUtilities.buildNodeUri(id);
                        ContentProviderOperation op = ContentProviderOperation.newUpdate(uri).withValues(values)
                                .build();
                        operations.add(op);
                        if (operations.size() > 10) {
                            try {
                                contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations);
                                operations.clear();
                            } catch (RemoteException e) {
                                Log.e(TAG, "Remote exception", e);
                            } catch (OperationApplicationException e) {
                                MetaUtilities.setIsCached(resourcePath, false);
                                return;
                            }
                            Thread.yield();
                        }
                    } else {
                        Log.v(TAG, "child up to date");
                    }
                } else {
                    // Insert node.
                    Log.v(TAG, "inserting child");
                    ContentProviderOperation op = ContentProviderOperation.newInsert(Nodes.CONTENT_URI)
                            .withValues(values).build();
                    operations.add(op);
                    if (operations.size() > 10) {
                        try {
                            contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations);
                            operations.clear();
                        } catch (RemoteException e) {
                            Log.e(TAG, "Remote exception", e);
                        } catch (OperationApplicationException e) {
                            MetaUtilities.setIsCached(resourcePath, false);
                            return;
                        }
                        Thread.yield();
                    }
                }
            } finally {
                c.close();
            }
        }

        @Override
        public void onUbuntuOneFailure(U1Failure failure) {
            MetaService.this.onUbuntuOneFailure(failure, receiver);
        }

        @Override
        public void onFailure(U1Failure failure) {
            MetaService.this.onFailure(failure, receiver);
        }

        @Override
        public void onFinish() {
            if (receiver != null)
                receiver.send(Status.FINISHED, data);
        }
    });

    // Remove nodes, which ids are left in childrenIds set.
    if (!childrenIds.isEmpty()) {
        Log.v(TAG, "childrenIDs not empty: " + childrenIds.size());
        final Iterator<Integer> it = childrenIds.iterator();
        while (it.hasNext()) {
            int id = it.next();
            Uri uri = MetaUtilities.buildNodeUri(id);
            ContentProviderOperation op = ContentProviderOperation.newDelete(uri).build();
            operations.add(op);
        }
    } else {
        Log.v(TAG, "childrenIDs empty");
    }

    try {
        long then = System.currentTimeMillis();
        contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations);
        MetaUtilities.setIsCached(resourcePath, true);
        long now = System.currentTimeMillis();
        Log.d(TAG, "time to update children: " + (now - then));
        contentResolver.notifyChange(Nodes.CONTENT_URI, null);
    } catch (RemoteException e) {
        Log.e(TAG, "", e);
    } catch (OperationApplicationException e) {
        MetaUtilities.setIsCached(resourcePath, false);
        return;
    }
}

From source file:id.ridon.keude.UpdateService.java

private ContentProviderOperation updateExistingApk(final Apk apk) {
    Uri uri = ApkProvider.getContentUri(apk);
    ContentValues values = apk.toContentValues();
    return ContentProviderOperation.newUpdate(uri).withValues(values).build();
}