Example usage for android.content ContentProviderOperation newInsert

List of usage examples for android.content ContentProviderOperation newInsert

Introduction

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

Prototype

public static Builder newInsert(Uri uri) 

Source Link

Document

Create a Builder suitable for building an insert ContentProviderOperation .

Usage

From source file:com.murrayc.galaxyzoo.app.QuestionFragment.java

/**
 * Avoid calling this from the main (UI) thread - StrictMode doesn't like it on at least API 15
 * and API 16./*  www .j  a  va  2  s . co  m*/
 *
 * @param classificationInProgress
 */
private void saveClassificationSync(final ClassificationInProgress classificationInProgress) {
    final String itemId = getItemId();
    if (TextUtils.equals(itemId, ItemsContentProvider.URI_PART_ITEM_ID_NEXT)) {
        Log.error("QuestionFragment.saveClassification(): Attempting to save with the 'next' ID.");
        return;
    }

    final Activity activity = getActivity();
    if (activity == null)
        return;

    final ContentResolver resolver = activity.getContentResolver();

    // Add the related Classification Answers:
    // Use a ContentProvider operation to perform operations together,
    // either completely or not at all, as a transaction.
    // This should prevent an incomplete classification from being uploaded
    // before we have finished adding it.
    //
    // We use the specific ArrayList<> subtype instead of List<> because
    // ContentResolver.applyBatch() takes an ArrayList for some reason.
    final ArrayList<ContentProviderOperation> ops = new ArrayList<>();

    int sequence = 0;
    final List<ClassificationInProgress.QuestionAnswer> answers = classificationInProgress.getAnswers();
    if (answers != null) {
        for (final ClassificationInProgress.QuestionAnswer answer : answers) {
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(ClassificationAnswer.CLASSIFICATION_ANSWERS_URI);
            final ContentValues valuesAnswers = new ContentValues();
            valuesAnswers.put(ClassificationAnswer.Columns.ITEM_ID, itemId);
            valuesAnswers.put(ClassificationAnswer.Columns.SEQUENCE, sequence);
            valuesAnswers.put(ClassificationAnswer.Columns.QUESTION_ID, answer.getQuestionId());
            valuesAnswers.put(ClassificationAnswer.Columns.ANSWER_ID, answer.getAnswerId());
            builder.withValues(valuesAnswers);
            ops.add(builder.build());

            //For instance, if the question has multiple-choice checkboxes to select before clicking
            //the "Done" answer:
            final List<String> checkboxIds = answer.getCheckboxIds();
            if (checkboxIds != null) {
                for (final String checkboxId : checkboxIds) {
                    builder = ContentProviderOperation
                            .newInsert(ClassificationCheckbox.CLASSIFICATION_CHECKBOXES_URI);
                    final ContentValues valuesCheckbox = new ContentValues();
                    valuesCheckbox.put(ClassificationCheckbox.Columns.ITEM_ID, itemId);
                    valuesCheckbox.put(ClassificationCheckbox.Columns.SEQUENCE, sequence);
                    valuesCheckbox.put(ClassificationCheckbox.Columns.QUESTION_ID, answer.getQuestionId());
                    valuesCheckbox.put(ClassificationCheckbox.Columns.CHECKBOX_ID, checkboxId);
                    builder.withValues(valuesCheckbox);
                    ops.add(builder.build());
                }
            }

            sequence++;
        }
    }

    //Mark the Item (Subject) as done:
    final Uri.Builder uriBuilder = Item.ITEMS_URI.buildUpon();
    uriBuilder.appendPath(getItemId());
    final ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(uriBuilder.build());
    final ContentValues values = new ContentValues();
    values.put(Item.Columns.DONE, true);
    values.put(Item.Columns.DATETIME_DONE, getCurrentDateTimeAsIso8601());
    values.put(Item.Columns.FAVORITE, classificationInProgress.isFavorite());
    builder.withValues(values);
    ops.add(builder.build());

    try {
        resolver.applyBatch(ClassificationAnswer.AUTHORITY, ops);
    } catch (final RemoteException | OperationApplicationException e) {
        //This should never happen, and would mean a loss of the current classification,
        //so let it crash the app and generate a report with a stacktrace,
        //because that's (slightly) better than just ignoring it.
        //
        //I guess that OperationApplicationException is not an unchecked exception,
        //because it could be caused by not just pure programmer error,
        //for instance if our data did not fulfill a Sqlite database constraint.
        Log.error("QuestionFragment. saveClassification(): Exception from applyBatch()", e);
        throw new RuntimeException("ContentResolver.applyBatch() failed.", e);
    }

    //The ItemsContentProvider will upload the classification later.
}

From source file:org.sufficientlysecure.keychain.util.ContactHelper.java

/**
 * Adds a key id to the given raw contact.
 * <p/>/*  w w w  .  ja  v a 2 s . com*/
 * This creates the link to OK in contact details
 */
private void writeContactKey(ArrayList<ContentProviderOperation> ops, long rawContactId, long masterKeyId,
        String keyName) {
    ops.add(referenceRawContact(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI),
            rawContactId)
                    .withValue(ContactsContract.Data.MIMETYPE, Constants.CUSTOM_CONTACT_DATA_MIME_TYPE)
                    .withValue(ContactsContract.Data.DATA1,
                            mContext.getString(R.string.contact_show_key, keyName))
                    .withValue(ContactsContract.Data.DATA2, masterKeyId).build());
}

From source file:com.google.android.apps.muzei.gallery.GallerySettingsActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
    if (requestCode != REQUEST_CHOOSE_PHOTOS || resultCode != RESULT_OK) {
        super.onActivityResult(requestCode, resultCode, result);
        return;/*ww w.jav  a2  s . com*/
    }

    if (result == null) {
        return;
    }

    // Add chosen items
    final Set<Uri> uris = new HashSet<>();
    if (result.getData() != null) {
        uris.add(result.getData());
    }
    // When selecting multiple images, "Photos" returns the first URI in getData and all URIs
    // in getClipData.
    ClipData clipData = result.getClipData();
    if (clipData != null) {
        int count = clipData.getItemCount();
        for (int i = 0; i < count; i++) {
            uris.add(clipData.getItemAt(i).getUri());
        }
    }

    // Update chosen URIs
    runOnHandlerThread(new Runnable() {
        @Override
        public void run() {
            ArrayList<ContentProviderOperation> operations = new ArrayList<>();
            for (Uri uri : uris) {
                ContentValues values = new ContentValues();
                values.put(GalleryContract.ChosenPhotos.COLUMN_NAME_URI, uri.toString());
                operations.add(ContentProviderOperation.newInsert(GalleryContract.ChosenPhotos.CONTENT_URI)
                        .withValues(values).build());
            }
            try {
                getContentResolver().applyBatch(GalleryContract.AUTHORITY, operations);
            } catch (RemoteException | OperationApplicationException e) {
                Log.e(TAG, "Error writing uris to ContentProvider", e);
            }
        }
    });
}

From source file:at.bitfire.vcard4android.AndroidContact.java

protected void insertPhoneNumber(BatchOperation batch, Telephone number) {
    int typeCode = Phone.TYPE_OTHER;
    String typeLabel = null;/*from   ww w.  j a  va  2s.c om*/

    Set<TelephoneType> types = number.getTypes();

    // preferred number?
    boolean is_primary = number.getPref() != null;
    if (types.contains(TelephoneType.PREF)) {
        is_primary = true;
        types.remove(TelephoneType.PREF);
    }

    // 1 Android type <-> 2 VCard types: fax, cell, pager
    if (types.contains(TelephoneType.FAX)) {
        if (types.contains(TelephoneType.HOME))
            typeCode = Phone.TYPE_FAX_HOME;
        else if (types.contains(TelephoneType.WORK))
            typeCode = Phone.TYPE_FAX_WORK;
        else
            typeCode = Phone.TYPE_OTHER_FAX;
    } else if (types.contains(TelephoneType.CELL)) {
        if (types.contains(TelephoneType.WORK))
            typeCode = Phone.TYPE_WORK_MOBILE;
        else
            typeCode = Phone.TYPE_MOBILE;
    } else if (types.contains(TelephoneType.PAGER)) {
        if (types.contains(TelephoneType.WORK))
            typeCode = Phone.TYPE_WORK_PAGER;
        else
            typeCode = Phone.TYPE_PAGER;
        // types with 1:1 translation
    } else if (types.contains(TelephoneType.HOME)) {
        typeCode = Phone.TYPE_HOME;
    } else if (types.contains(TelephoneType.WORK)) {
        typeCode = Phone.TYPE_WORK;
    } else if (types.contains(Contact.PHONE_TYPE_CALLBACK)) {
        typeCode = Phone.TYPE_CALLBACK;
    } else if (types.contains(TelephoneType.CAR)) {
        typeCode = Phone.TYPE_CAR;
    } else if (types.contains(Contact.PHONE_TYPE_COMPANY_MAIN)) {
        typeCode = Phone.TYPE_COMPANY_MAIN;
    } else if (types.contains(TelephoneType.ISDN)) {
        typeCode = Phone.TYPE_ISDN;
    } else if (types.contains(TelephoneType.VOICE)) {
        typeCode = Phone.TYPE_MAIN;
    } else if (types.contains(Contact.PHONE_TYPE_RADIO)) {
        typeCode = Phone.TYPE_RADIO;
    } else if (types.contains(TelephoneType.TEXTPHONE)) {
        typeCode = Phone.TYPE_TELEX;
    } else if (types.contains(TelephoneType.TEXT)) {
        typeCode = Phone.TYPE_TTY_TDD;
    } else if (types.contains(Contact.PHONE_TYPE_ASSISTANT)) {
        typeCode = Phone.TYPE_ASSISTANT;
    } else if (types.contains(Contact.PHONE_TYPE_MMS)) {
        typeCode = Phone.TYPE_MMS;
    } else if (!types.isEmpty()) {
        TelephoneType type = types.iterator().next();
        typeCode = Phone.TYPE_CUSTOM;
        typeLabel = xNameToLabel(type.getValue());
    }

    ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(dataSyncURI());
    if (id == null)
        builder.withValueBackReference(Phone.RAW_CONTACT_ID, 0);
    else
        builder.withValue(Phone.RAW_CONTACT_ID, id);
    builder.withValue(Phone.MIMETYPE, Phone.CONTENT_ITEM_TYPE).withValue(Phone.NUMBER, number.getText())
            .withValue(Phone.TYPE, typeCode).withValue(Phone.LABEL, typeLabel)
            .withValue(Phone.IS_PRIMARY, is_primary ? 1 : 0)
            .withValue(Phone.IS_SUPER_PRIMARY, is_primary ? 1 : 0);
    batch.enqueue(builder.build());
}

From source file:org.sufficientlysecure.keychain.util.ContactHelper.java

/**
 * Write all known email addresses of a key (derived from user ids) to a given raw contact
 *///from w  w w. j a  v  a  2  s . c  o m
private void writeContactEmail(ArrayList<ContentProviderOperation> ops, long rawContactId, long masterKeyId) {
    ops.add(selectByRawContactAndItemType(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI),
            rawContactId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE).build());
    Cursor ids = mContentResolver.query(UserPackets.buildUserIdsUri(masterKeyId),
            new String[] { UserPackets.USER_ID }, UserPackets.IS_REVOKED + "=0", null, null);
    if (ids != null) {
        while (ids.moveToNext()) {
            OpenPgpUtils.UserId userId = KeyRing.splitUserId(ids.getString(0));
            if (userId.email != null) {
                ops.add(referenceRawContact(
                        ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI), rawContactId)
                                .withValue(ContactsContract.Data.MIMETYPE,
                                        ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                                .withValue(ContactsContract.CommonDataKinds.Email.DATA, userId.email).build());
            }
        }
        ids.close();
    }
}

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

private void onChatBoxResult(LightWeightChatBox result) {
    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
    // Add chat box to DB before setting it as our current chat box,
    // so that we get notify when this chat box is changed (#131).
    // FIX ME: right now category is required for a chat box.
    // And that requirement is incorrect. So this will be fixed after
    // the DB Scheme is changed, probably (#142.)
    ChatBox chatBox = new ChatBox(result.getId(), result.getKey(), result.getName(), result.getFayeChannel(),
            result.getAlias());/*www.j  av a  2 s  .c  o m*/

    ContentValues chatBoxContentValues = ChatBoxTable.getContentValues(chatBox, " ");
    batch.add(ContentProviderOperation.newInsert(ChatWingContentProvider.getChatBoxesUri())
            .withValues(chatBoxContentValues).build());

    try {
        mActivityDelegate.getActivity().getContentResolver().applyBatch(ChatWingContentProvider.AUTHORITY,
                batch);
        mActivityDelegate.getDrawerLayout().closeDrawers();
        // Don't directly set chat box using mCurrentChatBoxManager here
        // because components are not ready and won't receive posted events.
        mRequestedChatboxId = result.getId();
    } catch (RemoteException e) {
        mActivityDelegate.handle(e, R.string.error_failed_to_save_chat_box);
    } catch (OperationApplicationException e) {
        mActivityDelegate.handle(e, R.string.error_failed_to_save_chat_box);
    }
    // Add bookmark to SyncedBookmarkTable
    CreateBookmarkIntentService.start(mActivityDelegate.getActivity(), result);
    mActivityDelegate.getDrawerLayout().closeDrawers();
    // Don't directly set chat box using mCurrentChatBoxManager here
    // because components are not ready and won't receive posted events.
    mRequestedChatboxId = result.getId();
}

From source file:at.bitfire.vcard4android.AndroidContact.java

protected void insertEmail(BatchOperation batch, ezvcard.property.Email email) {
    int typeCode = 0;
    String typeLabel = null;/*from w  w  w. j a v  a  2s . c om*/

    Set<EmailType> types = email.getTypes();

    // preferred email address?
    boolean is_primary = email.getPref() != null;
    if (types.contains(EmailType.PREF)) {
        is_primary = true;
        types.remove(EmailType.PREF);
    }

    for (EmailType type : types)
        if (type == EmailType.HOME)
            typeCode = Email.TYPE_HOME;
        else if (type == EmailType.WORK)
            typeCode = Email.TYPE_WORK;
        else if (type == Contact.EMAIL_TYPE_MOBILE)
            typeCode = Email.TYPE_MOBILE;
    if (typeCode == 0) {
        if (email.getTypes().isEmpty())
            typeCode = Email.TYPE_OTHER;
        else {
            typeCode = Email.TYPE_CUSTOM;
            typeLabel = xNameToLabel(email.getTypes().iterator().next().getValue());
        }
    }

    ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(dataSyncURI());
    if (id == null)
        builder.withValueBackReference(Email.RAW_CONTACT_ID, 0);
    else
        builder.withValue(Email.RAW_CONTACT_ID, id);
    builder.withValue(Email.MIMETYPE, Email.CONTENT_ITEM_TYPE).withValue(Email.ADDRESS, email.getValue())
            .withValue(Email.TYPE, typeCode).withValue(Email.LABEL, typeLabel)
            .withValue(Email.IS_PRIMARY, is_primary ? 1 : 0)
            .withValue(Phone.IS_SUPER_PRIMARY, is_primary ? 1 : 0);
    batch.enqueue(builder.build());
}

From source file:org.sufficientlysecure.keychain.util.ContactHelper.java

private ContentProviderOperation.Builder insertOrUpdateForRawContact(Uri uri, long rawContactId,
        String itemType) {/* w  ww .j  ava2s.c o  m*/
    if (rawContactId == -1) {
        return referenceRawContact(ContentProviderOperation.newInsert(uri), rawContactId)
                .withValue(ContactsContract.Data.MIMETYPE, itemType);
    } else {
        return selectByRawContactAndItemType(ContentProviderOperation.newUpdate(uri), rawContactId, itemType);
    }
}

From source file:org.kontalk.sync.Syncer.java

private ContentProviderOperation.Builder insertRawContact(Account account, String username, String phone,
        String jid, Uri uri) {//from w w  w .  ja  v  a 2 s  .  co m
    return ContentProviderOperation.newInsert(uri)
            .withValue(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DEFAULT)
            .withValue(RawContacts.ACCOUNT_NAME, account.name).withValue(RawContacts.ACCOUNT_TYPE, account.type)
            .withValue(RAW_COLUMN_DISPLAY_NAME, username).withValue(RAW_COLUMN_PHONE, phone)
            .withValue(RAW_COLUMN_USERID, jid);
}

From source file:at.bitfire.vcard4android.AndroidContact.java

protected void insertOrganization(BatchOperation batch) {
    if (contact.organization == null && contact.jobTitle == null && contact.jobDescription == null)
        return;/* w w w.  j  av a  2  s  .  c  om*/

    String company = null, department = null;
    ezvcard.property.Organization organization = contact.organization;
    if (organization != null) {
        Iterator<String> org = organization.getValues().iterator();
        if (org.hasNext())
            company = org.next();
        if (org.hasNext())
            department = org.next();
    }

    ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(dataSyncURI());
    if (id == null)
        builder.withValueBackReference(Organization.RAW_CONTACT_ID, 0);
    else
        builder.withValue(Organization.RAW_CONTACT_ID, id);
    builder.withValue(Organization.MIMETYPE, Organization.CONTENT_ITEM_TYPE)
            .withValue(Organization.COMPANY, company).withValue(Organization.DEPARTMENT, department)
            .withValue(Organization.TITLE, contact.jobTitle)
            .withValue(Organization.JOB_DESCRIPTION, contact.jobDescription);
    batch.enqueue(builder.build());
}