Example usage for android.content ContentProviderOperation newAssertQuery

List of usage examples for android.content ContentProviderOperation newAssertQuery

Introduction

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

Prototype

public static Builder newAssertQuery(Uri uri) 

Source Link

Document

Create a Builder suitable for building a ContentProviderOperation to assert a set of values as provided through Builder#withValues(ContentValues) .

Usage

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

private ContentProviderResult[] optimisticallyCreateGroupAndContacts(JSONObject group,
        ContentProviderClient provider, ContentProviderClient contactsProvider, String authToken,
        Account account, SyncResult syncResult)
        throws JSONException, RemoteException, OperationApplicationException {

    String groupCloudId = group.getString(JSONKeys.KEY_ID);
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    // If the first operation asserts, that means the group already exists
    // Operation 0
    ContentProviderOperation.Builder op = ContentProviderOperation.newAssertQuery(GMSGroups.CONTENT_URI)
            .withValue(GMSGroup._ID, "").withValue(GMSGroup.CLOUD_ID, "")
            .withSelection(GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }).withExpectedCount(0);
    ops.add(op.build());/*from ww  w .j  a  va 2 s.c o m*/
    // If we get this far, create the group from the information the JSON object
    // Operation 1
    ContentValues groupValues = GMSApplication.getGroupValues(group);
    op = ContentProviderOperation.newInsert(GMSGroups.CONTENT_URI).withValues(groupValues)
            .withValue(GMSGroup.STATUS, GMSGroup.STATUS_SYNCED);
    ops.add(op.build());
    // And add the contacts
    // Operations 2 - N + 2 where N is the number of members in group
    if (group.has(JSONKeys.KEY_MEMBERS)) {
        JSONArray membersArray = group.getJSONArray(JSONKeys.KEY_MEMBERS);
        int numMembers = membersArray.length();
        for (int j = 0; j < numMembers; ++j) {
            JSONObject member = membersArray.getJSONObject(j);
            ContentValues memberValues = GMSApplication.getMemberValues(member);
            op = ContentProviderOperation.newInsert(GMSContacts.CONTENT_URI).withValues(memberValues)
                    .withValueBackReference(GMSContact.GROUP_ID, 1)
                    .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED);
            ops.add(op.build());
        }
    }
    ContentProviderResult[] results = provider.applyBatch(ops);
    // Create the contact on the device
    Uri groupUri = results[1].uri;
    if (groupUri != null) {
        Cursor cursor = null;
        try {
            cursor = GMSContactOperations.findGroupInContacts(contactsProvider, account, groupCloudId);
            if (cursor.getCount() > 0) {
                Assert.assertTrue(cursor.moveToFirst());
                long oldContactId = cursor.getLong(0);
                GMSContactOperations.removeGroupFromContacts(contactsProvider, account, oldContactId,
                        syncResult);
            }
            long contactId = GMSContactOperations.addGroupToContacts(getContext(), contactsProvider, account,
                    group, syncResult);
            if (contactId > 0) {
                ContentValues values = new ContentValues();
                values.put(GMSGroup.RAW_CONTACT_ID, contactId);
                provider.update(groupUri, values, null, null);
                addNewGroupNotification(group);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    return results;
}

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

private ContentProviderResult[] optimisticallyUpdateGroup(JSONObject group, ContentProviderClient provider,
        ContentProviderClient contactsProvider, String authToken, Account account, SyncResult syncResult)
        throws JSONException, RemoteException {

    String groupCloudId = null;//from   w  w w.  j  av  a  2s.c o  m
    String version = null;
    try {
        groupCloudId = group.getString(JSONKeys.KEY_ID);
        version = group.getString(JSONKeys.KEY_VERSION);

        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        // Operation 0 - we believe the record exists, but we'll check, inside a transaction, to make sure
        ContentProviderOperation op;
        op = ContentProviderOperation.newAssertQuery(GMSGroups.CONTENT_URI)
                .withSelection(GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }).withExpectedCount(1)
                .build();
        ops.add(op);
        // Operation 1 - 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(GMSGroups.CONTENT_URI)
                .withSelection(GMSGroup.CLOUD_ID + "=? AND " + GMSGroup.VERSION + "=?",
                        new String[] { groupCloudId, version })
                .withExpectedCount(0).build();
        ops.add(op);
        // If we get this far, update the existing group from the information in the JSON object
        // Operation 2
        ContentValues groupValues = GMSApplication.getGroupValues(group);
        op = ContentProviderOperation.newUpdate(GMSGroups.CONTENT_URI)
                .withSelection(GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }).withValues(groupValues)
                .withValue(GMSGroup.STATUS, GMSGroup.STATUS_SYNCED).withExpectedCount(1).build();
        ops.add(op);
        return provider.applyBatch(ops);
    } catch (OperationApplicationException e) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        ContentProviderOperation op;
        // 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(GMSGroups.CONTENT_URI)
                .withSelection(GMSGroup.CLOUD_ID + "=? AND " + GMSGroup.VERSION + "=?",
                        new String[] { groupCloudId, version })
                .withExpectedCount(1).build();
        ops.add(op);
        // If we get this far we only need to update the is_synced field in the database
        // Operation 1
        op = ContentProviderOperation.newUpdate(GMSGroups.CONTENT_URI)
                .withSelection(GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId })
                .withValue(GMSGroup.STATUS, GMSGroup.STATUS_SYNCED).withExpectedCount(1).build();
        ops.add(op);
        try {
            return provider.applyBatch(ops);
        } catch (OperationApplicationException e1) {
            e1.printStackTrace();
            syncResult.stats.numSkippedEntries++;
        }
    }
    return null;
}

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  . j  a  va2 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();
        }
    }
}

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

private void addMembersToGroup(ContentResolver resolver, long[] rawContactsToAdd, long groupId) {
    if (rawContactsToAdd == null) {
        return;// w w  w .  j  ava  2s.  com
    }
    for (long rawContactId : rawContactsToAdd) {
        try {
            final ArrayList<ContentProviderOperation> rawContactOperations = new ArrayList<ContentProviderOperation>();

            // Build an assert operation to ensure the contact is not already in the group
            final ContentProviderOperation.Builder assertBuilder = ContentProviderOperation
                    .newAssertQuery(Data.CONTENT_URI);
            assertBuilder.withSelection(
                    Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "=? AND " + GroupMembership.GROUP_ROW_ID
                            + "=?",
                    new String[] { String.valueOf(rawContactId), GroupMembership.CONTENT_ITEM_TYPE,
                            String.valueOf(groupId) });
            assertBuilder.withExpectedCount(0);
            rawContactOperations.add(assertBuilder.build());

            // Build an insert operation to add the contact to the group
            final ContentProviderOperation.Builder insertBuilder = ContentProviderOperation
                    .newInsert(Data.CONTENT_URI);
            insertBuilder.withValue(Data.RAW_CONTACT_ID, rawContactId);
            insertBuilder.withValue(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
            insertBuilder.withValue(GroupMembership.GROUP_ROW_ID, groupId);
            rawContactOperations.add(insertBuilder.build());

            if (DEBUG) {
                for (ContentProviderOperation operation : rawContactOperations) {
                    Log.v(TAG, operation.toString());
                }
            }

            // Apply batch
            if (!rawContactOperations.isEmpty()) {
                resolver.applyBatch(ContactsContract.AUTHORITY, rawContactOperations);
            }
        } catch (RemoteException e) {
            // Something went wrong, bail without success
            FeedbackHelper.sendFeedback(this, TAG,
                    "Problem persisting user edits for raw contact ID " + String.valueOf(rawContactId), e);
        } catch (OperationApplicationException e) {
            // The assert could have failed because the contact is already in the group,
            // just continue to the next contact
            FeedbackHelper.sendFeedback(this, TAG, "Assert failed in adding raw contact ID "
                    + String.valueOf(rawContactId) + ". Already exists in group " + String.valueOf(groupId), e);
        }
    }
}