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.battlelancer.seriesguide.ui.dialogs.ListsDialogFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View layout = inflater.inflate(R.layout.list_dialog, null);

    // buttons//from  www  .  j ava 2 s .c  o  m
    Button dontAddButton = (Button) layout.findViewById(R.id.buttonNegative);
    dontAddButton.setText(android.R.string.cancel);
    dontAddButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    });
    Button addButton = (Button) layout.findViewById(R.id.buttonPositive);
    addButton.setText(android.R.string.ok);
    addButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // add item to selected lists
            String itemId = getArguments().getString("itemid");
            int itemType = getArguments().getInt("itemtype");
            SparseBooleanArray checkedLists = mAdapter.getCheckedPositions();

            final ArrayList<ContentProviderOperation> batch = com.uwetrottmann.androidutils.Lists
                    .newArrayList();

            for (int position = 0; position < mAdapter.getCount(); position++) {
                final Cursor listEntry = (Cursor) mAdapter.getItem(position);

                boolean wasListChecked = !TextUtils.isEmpty(listEntry.getString(ListsQuery.LIST_ITEM_ID));
                boolean isListChecked = checkedLists.get(position);

                String listId = listEntry.getString(ListsQuery.LIST_ID);
                String listItemId = ListItems.generateListItemId(itemId, itemType, listId);

                if (wasListChecked && !isListChecked) {
                    // remove from list
                    batch.add(
                            ContentProviderOperation.newDelete(ListItems.buildListItemUri(listItemId)).build());
                } else if (!wasListChecked && isListChecked) {
                    // add to list
                    ContentValues values = new ContentValues();
                    values.put(ListItems.LIST_ITEM_ID, listItemId);
                    values.put(ListItems.ITEM_REF_ID, itemId);
                    values.put(ListItems.TYPE, itemType);
                    values.put(Lists.LIST_ID, listId);
                    batch.add(ContentProviderOperation.newInsert(ListItems.CONTENT_URI).withValues(values)
                            .build());
                }
            }

            // apply ops
            try {
                DBUtils.applyInSmallBatches(getActivity(), batch);
            } catch (OperationApplicationException e) {
                Timber.e("Applying list changes failed", e);
            }

            getActivity().getContentResolver().notifyChange(ListItems.CONTENT_WITH_DETAILS_URI, null);

            dismiss();
        }
    });

    // lists list
    mListView = (ListView) layout.findViewById(R.id.list);
    /*
     * As using CHOICE_MODE_MULTIPLE does not seem to work before Jelly
     * Bean, do everything ourselves.
     */
    mListView.setOnItemClickListener(this);

    return layout;
}

From source file:com.nineash.hutsync.client.NetworkUtilities.java

private static long getCalendar(Account account) {
    // Find the Last.fm calendar if we've got one
    Uri calenderUri = Calendars.CONTENT_URI.buildUpon()
            .appendQueryParameter(Calendars.ACCOUNT_NAME, account.name)
            .appendQueryParameter(Calendars.ACCOUNT_TYPE, account.type).build();
    Cursor c1 = mContentResolver.query(calenderUri, new String[] { BaseColumns._ID }, null, null, null);
    if (c1.moveToNext()) {
        long ret = c1.getLong(0);
        c1.close();/*from w  w w.ja v  a  2  s .co  m*/
        return ret;
    } else {
        ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();

        ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(Calendars.CONTENT_URI
                .buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                .appendQueryParameter(Calendars.ACCOUNT_NAME, account.name)
                .appendQueryParameter(Calendars.ACCOUNT_TYPE, account.type).build());
        builder.withValue(Calendars.ACCOUNT_NAME, account.name);
        builder.withValue(Calendars.ACCOUNT_TYPE, account.type);
        builder.withValue(Calendars.NAME, "Pizza Hut Shifts");
        builder.withValue(Calendars.CALENDAR_DISPLAY_NAME, "Pizza Hut Shifts");
        builder.withValue(Calendars.CALENDAR_COLOR, 0xD51007);
        builder.withValue(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_READ);
        builder.withValue(Calendars.OWNER_ACCOUNT, account.name);
        builder.withValue(Calendars.SYNC_EVENTS, 1);
        operationList.add(builder.build());
        try {
            mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return -1;
        }
        c1.close();
        return getCalendar(account);
    }
}

From source file:fr.mixit.android.io.JsonHandlerApplyMembers.java

@Override
public boolean parseItem(JSONObject item, ContentResolver resolver) throws JSONException {
    final String id = item.getString(TAG_ID);
    mItemIds.add(id);//  w  w w  .j  a  v a2 s . co  m

    final Uri itemUri = MixItContract.Members.buildMemberUri(id);

    boolean tagUpdated = false;
    boolean newItem = false;
    boolean build = false;
    ContentProviderOperation.Builder builder;

    if (ProviderParsingUtils.isRowExisting(itemUri, MixItContract.Members.PROJ_DETAIL.PROJECTION, resolver)) {
        builder = ContentProviderOperation.newUpdate(itemUri);
        tagUpdated = isItemUpdated(itemUri, item, resolver, mMemberType);
    } else {
        newItem = true;
        builder = ContentProviderOperation.newInsert(MixItContract.Members.CONTENT_URI);
        builder.withValue(MixItContract.Members.MEMBER_ID, id);
        builder.withValue(MixItContract.Members.TYPE, mMemberType);
        build = true;
    }

    if (newItem || tagUpdated) {
        if (item.has(TAG_FIRSTNAME)) {
            final String firstName = item.getString(TAG_FIRSTNAME);
            // if (!TextUtils.isEmpty(firstName)) {
            // firstName = firstName.toLowerCase(Locale.getDefault());
            // final String[] firstNames = firstName.split(" ");
            // if (firstNames.length > 1) {
            // firstName = null;
            // for (int i = 0; i < firstNames.length; i++) {
            // firstName += firstNames[i].substring(0, 1).toUpperCase(Locale.getDefault()) + firstNames[i].substring(1);
            // }
            //
            // } else {
            // firstName = firstName.substring(0, 1).toUpperCase(Locale.getDefault()) + firstName.substring(1);
            // }
            // }
            builder.withValue(MixItContract.Members.FIRSTNAME, firstName);
        }
        if (item.has(TAG_LASTNAME)) {
            final String lastName = item.getString(TAG_LASTNAME);
            // if (!TextUtils.isEmpty(lastName)) {
            // lastName = lastName.toLowerCase(Locale.getDefault());
            // lastName = lastName.substring(0, 1).toUpperCase(Locale.getDefault()) + lastName.substring(1);
            // }
            builder.withValue(MixItContract.Members.LASTNAME, lastName);
        }
        if (item.has(TAG_LOGIN)) {
            builder.withValue(MixItContract.Members.LOGIN, item.getString(TAG_LOGIN));
        }
        if (item.has(TAG_COMPANY)) {
            builder.withValue(MixItContract.Members.COMPANY, item.getString(TAG_COMPANY));
        }
        if (item.has(TAG_SHORT_DESC)) {
            builder.withValue(MixItContract.Members.SHORT_DESC, item.getString(TAG_SHORT_DESC));
        }
        if (item.has(TAG_LONG_DESC)) {
            builder.withValue(MixItContract.Members.LONG_DESC, item.getString(TAG_LONG_DESC));
        }
        if (item.has(TAG_LOGO)) {
            builder.withValue(MixItContract.Members.IMAGE_URL, item.getString(TAG_LOGO));
        } else if (item.has(TAG_IMAGE_URL) && mMemberType != MixItContract.Members.TYPE_SPONSOR) {
            builder.withValue(MixItContract.Members.IMAGE_URL, item.getString(TAG_IMAGE_URL));
        }
        if (item.has(TAG_NB_CONSULTS)) {
            builder.withValue(MixItContract.Members.NB_CONSULT, item.getString(TAG_NB_CONSULTS));
        }
        if (item.has(TAG_LEVEL)) {
            builder.withValue(MixItContract.Members.LEVEL, item.getString(TAG_LEVEL));
        }

        build = true;
    }
    if (build) {
        ProviderParsingUtils.addOpeAndApplyBatch(mAuthority, resolver, mBatch, false, builder.build());
    }

    if (mIsFullParsing) {
        if (item.has(TAG_LINKS)) {
            final JSONArray interests = item.getJSONArray(TAG_LINKS);
            parseLinks(id, interests, resolver);
        }
        if (item.has(TAG_LINKERS)) {
            final JSONArray interests = item.getJSONArray(TAG_LINKERS);
            parseLinkers(id, interests, resolver);
        }
        if (item.has(TAG_INTERESTS)) {
            final JSONArray interests = item.getJSONArray(TAG_INTERESTS);
            parseLinkedInterests(id, interests, resolver);
        }
        if (item.has(TAG_SHARED_LINKS)) {
            final JSONArray interests = item.getJSONArray(TAG_SHARED_LINKS);
            parseSharedLinks(id, interests, resolver);
        }
    }

    if (!mIsParsingList) {
        deleteItemsDataNotFound(resolver);

        return ProviderParsingUtils.applyBatch(mAuthority, resolver, mBatch, true);
    }

    return true;
}

From source file:com.battlelancer.seriesguide.ui.dialogs.ManageListsDialogFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View layout = inflater.inflate(R.layout.dialog_manage_lists, container, false);

    // buttons//ww  w  . j ava2  s .  c o  m
    Button dontAddButton = (Button) layout.findViewById(R.id.buttonNegative);
    dontAddButton.setText(android.R.string.cancel);
    dontAddButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    });
    Button addButton = (Button) layout.findViewById(R.id.buttonPositive);
    addButton.setText(android.R.string.ok);
    addButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // add item to selected lists
            int itemTvdbId = getArguments().getInt(InitBundle.INT_ITEM_TVDB_ID);
            int itemType = getArguments().getInt(InitBundle.INT_ITEM_TYPE);
            SparseBooleanArray checkedLists = mAdapter.getCheckedPositions();

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

            for (int position = 0; position < mAdapter.getCount(); position++) {
                final Cursor listEntry = (Cursor) mAdapter.getItem(position);

                boolean wasListChecked = !TextUtils.isEmpty(listEntry.getString(ListsQuery.LIST_ITEM_ID));
                boolean isListChecked = checkedLists.get(position);

                String listId = listEntry.getString(ListsQuery.LIST_ID);
                String listItemId = ListItems.generateListItemId(itemTvdbId, itemType, listId);

                if (wasListChecked && !isListChecked) {
                    // remove from list
                    batch.add(
                            ContentProviderOperation.newDelete(ListItems.buildListItemUri(listItemId)).build());
                } else if (!wasListChecked && isListChecked) {
                    // add to list
                    ContentValues values = new ContentValues();
                    values.put(ListItems.LIST_ITEM_ID, listItemId);
                    values.put(ListItems.ITEM_REF_ID, itemTvdbId);
                    values.put(ListItems.TYPE, itemType);
                    values.put(Lists.LIST_ID, listId);
                    batch.add(ContentProviderOperation.newInsert(ListItems.CONTENT_URI).withValues(values)
                            .build());
                }
            }

            // apply ops
            try {
                DBUtils.applyInSmallBatches(getActivity(), batch);
            } catch (OperationApplicationException e) {
                Timber.e(e, "Applying list changes failed");
            }

            getActivity().getContentResolver().notifyChange(ListItems.CONTENT_WITH_DETAILS_URI, null);

            dismiss();
        }
    });

    // lists list
    mListView = (ListView) layout.findViewById(R.id.list);
    /*
     * As using CHOICE_MODE_MULTIPLE does not seem to work before Jelly
     * Bean, do everything ourselves.
     */
    mListView.setOnItemClickListener(this);

    return layout;
}

From source file:edu.mit.mobile.android.demomode.Preferences.java

private void fromCfgString(String cfg) {
    final Uri cfgUri = Uri.parse(cfg);
    if ("data".equals(cfgUri.getScheme())) {
        final String[] cfgParts = cfgUri.getEncodedSchemeSpecificPart().split(",", 2);
        if (CFG_MIME_TYPE.equals(cfgParts[0])) {
            final Editor ed = mPrefs.edit();
            final ArrayList<ContentProviderOperation> cpos = new ArrayList<ContentProviderOperation>();

            // first erase everything
            cpos.add(ContentProviderOperation.newDelete(LauncherItem.CONTENT_URI).build());

            try {
                final StringEntity entity = new StringEntity(cfgParts[1]);
                entity.setContentType("application/x-www-form-urlencoded");
                final List<NameValuePair> nvp = URLEncodedUtils.parse(entity);
                for (final NameValuePair pair : nvp) {
                    final String name = pair.getName();
                    Log.d(TAG, "parsed pair: " + pair);
                    if (CFG_K_SECRETKEY.equals(name)) {
                        ed.putString(KEY_PASSWORD, pair.getValue());

                    } else if (CFG_K_APPS.equals(name)) {
                        final String[] app = pair.getValue().split(CFG_PKG_SEP, 2);
                        final ContentProviderOperation cpo = ContentProviderOperation
                                .newInsert(LauncherItem.CONTENT_URI)
                                .withValue(LauncherItem.PACKAGE_NAME, app[0])
                                .withValue(LauncherItem.ACTIVITY_NAME, app[1]).build();
                        cpos.add(cpo);//from  w ww.ja v a  2  s.c  om
                        Log.d(TAG, "adding " + cpo);
                    }
                }

                ed.commit();
                getContentResolver().applyBatch(HomescreenProvider.AUTHORITY, cpos);
            } catch (final UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (final IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (final RemoteException e) {
                // TODO Auto-generated catch block

                e.printStackTrace();
            } catch (final OperationApplicationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            Log.e(TAG, "unknown MIME type for data URI: " + cfgParts[0]);
        }

    } else {
        Log.e(TAG, "not a data URI");
    }
}

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());//  ww  w .ja  v  a  2  s.  co  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:org.codarama.haxsync.services.ContactsSyncAdapterService.java

private static void addSelfContact(Account account, int maxSize, boolean square, boolean faceDetect,
        boolean force, boolean root, int rootsize, File cacheDir, boolean google) {

    Uri rawContactUri = ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI.buildUpon()
            .appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
            .appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type).build();

    long ID = -2;
    String username;/*from  www. ja v a  2  s  .  c o m*/
    String email;
    FacebookGraphFriend user = FacebookUtil.getSelfInfo();
    if (user == null)
        return;
    Cursor cursor = mContentResolver.query(rawContactUri, new String[] { BaseColumns._ID, UsernameColumn },
            null, null, null);
    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        ID = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
        username = cursor.getString(cursor.getColumnIndex(UsernameColumn));
        cursor.close();
    } else {
        cursor.close();
        username = user.getUserName();
        email = user.getEmail();

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

        ContentProviderOperation.Builder builder = ContentProviderOperation
                .newInsert(ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI);
        builder.withValue(RawContacts.ACCOUNT_NAME, account.name);
        builder.withValue(RawContacts.ACCOUNT_TYPE, account.type);
        builder.withValue(RawContacts.SYNC1, username);
        operationList.add(builder.build());

        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, account.name);
        operationList.add(builder.build());

        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                "vnd.android.cursor.item/vnd.org.codarama.haxsync.profile");
        builder.withValue(ContactsContract.Data.DATA1, username);
        builder.withValue(ContactsContract.Data.DATA2, "Facebook Profile");
        builder.withValue(ContactsContract.Data.DATA3, "View profile");
        operationList.add(builder.build());

        if (email != null) {
            builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
            builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
            builder.withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
            builder.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
            operationList.add(builder.build());
        }

        try {
            mContentResolver.applyBatch(ContactsContract.AUTHORITY, operationList);
        } catch (Exception e) {
            // FIXME catching generic Exception class is not the best thing to do
            Log.e("Error", e.getLocalizedMessage());
            return;
        }
        cursor = mContentResolver.query(rawContactUri, new String[] { BaseColumns._ID }, null, null, null);
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            ID = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
            cursor.close();
        } else {
            Log.i(TAG, "NO SELF CONTACT FOUND");
            return;
        }
    }
    Log.i("self contact", "id: " + ID + " uid: " + username);
    if (ID != -2 && username != null) {

        updateContactPhoto(ID, 0, maxSize, square, user.getPicURL(), faceDetect, true, root, rootsize, cacheDir,
                google, true);

    }
}

From source file:com.grokkingandroid.sampleapp.samples.data.contentprovider.lentitems.LentItemDisplayFragment.java

/**
 * The dummyApplyBatch method is only used to show a sample batch. 
 * It's not used within this sample app.
 *///from  ww w  .j  ava 2s .  co m
@SuppressWarnings("unused")
private void dummyApplyBatch() {

    String borrower = "John Doe";
    String item = "Anhalter";
    boolean hasPic = true;
    Context ctx = getActivity();
    String somePath = ctx.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newInsert(Items.CONTENT_URI).withValue(Items.NAME, item)
            .withValue(Items.BORROWER, borrower).build());
    if (hasPic) {
        ops.add(ContentProviderOperation.newInsert(Photos.CONTENT_URI).withValue(Photos._DATA, somePath)
                .withValueBackReference(Photos.ITEMS_ID, 0).build());
    }
    try {
        ContentResolver resolver = getActivity().getContentResolver();
        resolver.applyBatch(LentItemsContract.AUTHORITY, ops);
    } catch (OperationApplicationException e) {
        Log.e("wemonit", "cannot apply batch: " + e.getLocalizedMessage(), e);
    } catch (RemoteException e) {
        Log.e("wemonit", "cannot apply batch: " + e.getLocalizedMessage(), e);
    }

    // EventBus.getDefault().post(whatever);

}

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

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

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

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

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

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

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

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

    try {
        if (photo != null) {
            builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
            builder.withValue(ContactsContract.CommonDataKinds.Photo.RAW_CONTACT_ID, rawContactId);
            builder.withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
            builder.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photo);
            operationList.add(builder.build());

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