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.asalfo.wiulgi.util.Utils.java

private static ContentProviderOperation buildBatchOperation(@NonNull Item item) {

    Uri dirUri = WiulgiContract.Items.buildDirUri();
    ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(dirUri);

    LatLng cord = item.getLocation();/*from w  ww. j  av  a 2  s .com*/

    builder.withValue(ItemsColumns.MONGO_ID, item.getMongoId());
    builder.withValue(ItemsColumns.TITLE, item.getTitle());
    builder.withValue(ItemsColumns.SLUG, item.getSlug());
    builder.withValue(ItemsColumns.DESCRIPTION, item.getDescription());
    builder.withValue(ItemsColumns.PRICE, item.getPrice());
    builder.withValue(ItemsColumns.MODEL, item.getModel());
    builder.withValue(ItemsColumns.BRAND, item.getBrand());
    builder.withValue(ItemsColumns.COLOR, item.getColor());
    builder.withValue(ItemsColumns.SIZE, item.getSize());
    if (null != item.getLocation()) {
        builder.withValue(ItemsColumns.LATITUDE, item.getLocation().latitude);
        builder.withValue(ItemsColumns.LONGITUDE, item.getLocation().longitude);
    }
    builder.withValue(ItemsColumns.THUMBNAIL, item.getThumbnail());
    builder.withValue(ItemsColumns.VOTE_AVERAGE, item.getVoteAverage());
    builder.withValue(ItemsColumns.VOTE_COUNT, item.getVoteCount());

    return builder.build();
}

From source file:com.nononsenseapps.feeder.model.RssSyncHelper.java

/**
 * Adds the information contained in the feed to the list of pending
 * operations, to be committed with applyBatch.
 *
 * @param context/*from w  w w.  jav a  2s  . c  o m*/
 * @param operations
 * @param feed
 */
public static void syncFeedBatch(final Context context, final ArrayList<ContentProviderOperation> operations,
        final BackendAPIClient.Feed feed) {

    // This is the index of the feed, if needed for backreferences
    final int feedIndex = operations.size();

    // Create the insert/update feed operation first
    final ContentProviderOperation.Builder feedOp;
    // Might not exist yet
    final long feedId = getFeedSQLId(context, feed);
    if (feedId < 1) {
        feedOp = ContentProviderOperation.newInsert(FeedSQL.URI_FEEDS);
    } else {
        feedOp = ContentProviderOperation
                .newUpdate(Uri.withAppendedPath(FeedSQL.URI_FEEDS, Long.toString(feedId)));
    }
    // Populate with values
    feedOp.withValue(FeedSQL.COL_TITLE, feed.title).withValue(FeedSQL.COL_TAG, feed.tag == null ? "" : feed.tag)
            .withValue(FeedSQL.COL_TIMESTAMP, feed.timestamp).withValue(FeedSQL.COL_URL, feed.link);
    // Add to list of operations
    operations.add(feedOp.build());

    // Now the feeds, might be null
    if (feed.items == null) {
        return;
    }

    for (BackendAPIClient.FeedItem item : feed.items) {
        // Always insert, have on conflict clause
        ContentProviderOperation.Builder itemOp = ContentProviderOperation
                .newInsert(FeedItemSQL.URI_FEED_ITEMS);

        // First, reference feed's id with back ref if insert
        if (feedId < 1) {
            itemOp.withValueBackReference(FeedItemSQL.COL_FEED, feedIndex);
        } else {
            // Use the actual id, because update operation will not return id
            itemOp.withValue(FeedItemSQL.COL_FEED, feedId);
        }
        // Next all the other values. Make sure non null
        itemOp.withValue(FeedItemSQL.COL_GUID, item.guid).withValue(FeedItemSQL.COL_LINK, item.link)
                .withValue(FeedItemSQL.COL_FEEDTITLE, feed.title)
                .withValue(FeedItemSQL.COL_TAG, feed.tag == null ? "" : feed.tag)
                .withValue(FeedItemSQL.COL_IMAGEURL, item.image).withValue(FeedItemSQL.COL_JSON, item.json)
                .withValue(FeedItemSQL.COL_ENCLOSURELINK, item.enclosure)
                .withValue(FeedItemSQL.COL_AUTHOR, item.author)
                .withValue(FeedItemSQL.COL_PUBDATE, FeedItemSQL.getPubDateFromString(item.published))
                // Make sure these are non-null
                .withValue(FeedItemSQL.COL_TITLE, item.title == null ? "" : item.title)
                .withValue(FeedItemSQL.COL_DESCRIPTION, item.description == null ? "" : item.description)
                .withValue(FeedItemSQL.COL_PLAINTITLE, item.title_stripped == null ? "" : item.title_stripped)
                .withValue(FeedItemSQL.COL_PLAINSNIPPET, item.snippet == null ? "" : item.snippet);

        // Add to list of operations
        operations.add(itemOp.build());

        // TODO pre-cache all images
    }
}

From source file:io.nuclei.box.Query.java

public ContentProviderOperation toReplaceOperation(T object) {
    if (opType != QUERY_OPERATION_INSERT)
        throw new IllegalArgumentException("Not an insert query");
    if (contentValuesMapper == null)
        throw new IllegalArgumentException("Content Values Mapper is null");
    ContentValues values = contentValuesMapper.map(object);
    values.put(ContentProviderBase.REPLACE_RECORD, true);
    return ContentProviderOperation.newInsert(uri).withValues(values).build();
}

From source file:org.muckebox.android.net.RefreshHelper.java

public static Integer refreshArtists() {
    try {//from ww w .j  av  a 2s. c  o  m
        JSONArray json = ApiHelper.callApiForArray("artists");
        ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(
                json.length() + 1);

        operations.add(ContentProviderOperation.newDelete(MuckeboxProvider.URI_ARTISTS).build());

        for (int i = 0; i < json.length(); ++i) {
            JSONObject o = json.getJSONObject(i);
            operations.add(ContentProviderOperation.newInsert(MuckeboxProvider.URI_ARTISTS)
                    .withValue(ArtistEntry.SHORT_ID, o.getInt("id"))
                    .withValue(ArtistEntry.SHORT_NAME, o.getString("name")).build());
        }

        Muckebox.getAppContext().getContentResolver().applyBatch(MuckeboxProvider.AUTHORITY, operations);
    } catch (AuthenticationException e) {
        return R.string.error_authentication;
    } catch (SSLException e) {
        return R.string.error_ssl;
    } catch (IOException e) {
        Log.d(LOG_TAG, "IOException: " + e.getMessage());
        return R.string.error_reload_artists;
    } catch (JSONException e) {
        return R.string.error_json;
    } catch (RemoteException e) {
        e.printStackTrace();
        return R.string.error_reload_artists;
    } catch (OperationApplicationException e) {
        e.printStackTrace();
        return R.string.error_reload_artists;
    }

    return null;
}

From source file:net.peterkuterna.android.apps.devoxxsched.io.RemoteSessionsHandler.java

@Override
public ArrayList<ContentProviderOperation> parse(ArrayList<JSONArray> entries, ContentResolver resolver)
        throws JSONException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
    final HashSet<String> sessionIds = Sets.newHashSet();
    final HashSet<String> trackIds = Sets.newHashSet();
    final HashMap<String, HashSet<String>> sessionSpeakerIds = Maps.newHashMap();
    final HashMap<String, HashSet<String>> sessionTagIds = Maps.newHashMap();

    int nrEntries = 0;
    for (JSONArray sessions : entries) {
        Log.d(TAG, "Retrieved " + sessions.length() + " presentation entries.");
        nrEntries += sessions.length();//from  w w  w  .j  a  va2  s .  c  o m

        for (int i = 0; i < sessions.length(); i++) {
            JSONObject session = sessions.getJSONObject(i);
            String id = session.getString("id");

            final String sessionId = sanitizeId(id);
            final Uri sessionUri = Sessions.buildSessionUri(sessionId);
            sessionIds.add(sessionId);
            int isStarred = isStarred(sessionUri, resolver);

            boolean sessionUpdated = false;
            boolean newSession = false;
            ContentProviderOperation.Builder builder;
            if (isRowExisting(sessionUri, SessionsQuery.PROJECTION, resolver)) {
                builder = ContentProviderOperation.newUpdate(sessionUri);
                builder.withValue(Sessions.NEW, false);
                sessionUpdated = isSessionUpdated(sessionUri, session, resolver);
                if (isRemoteSync()) {
                    builder.withValue(Sessions.UPDATED, sessionUpdated);
                }
            } else {
                newSession = true;
                builder = ContentProviderOperation.newInsert(Sessions.CONTENT_URI);
                builder.withValue(Sessions.SESSION_ID, sessionId);
                if (!isLocalSync()) {
                    builder.withValue(Sessions.NEW, true);
                }
            }

            final String type = session.getString("type");
            if (newSession || sessionUpdated) {
                builder.withValue(Sessions.TITLE, session.getString("title"));
                builder.withValue(Sessions.EXPERIENCE, session.getString("experience"));
                builder.withValue(Sessions.TYPE, type);
                builder.withValue(Sessions.SUMMARY, session.getString("summary"));
                builder.withValue(Sessions.STARRED, isStarred);
            }
            builder.withValue(Sessions.TYPE_ID, getTypeId(type));

            batch.add(builder.build());

            if (session.has("track")) {
                final String trackName = session.getString("track");
                final String trackId = Tracks.generateTrackId(trackName);
                final Uri trackUri = Tracks.buildTrackUri(trackId);

                if (!trackIds.contains(trackId)) {
                    trackIds.add(trackId);

                    ContentProviderOperation.Builder trackBuilder;
                    if (isRowExisting(Tracks.buildTrackUri(trackId), TracksQuery.PROJECTION, resolver)) {
                        trackBuilder = ContentProviderOperation.newUpdate(trackUri);
                    } else {
                        trackBuilder = ContentProviderOperation.newInsert(Tracks.CONTENT_URI);
                        trackBuilder.withValue(Tracks.TRACK_ID, trackId);
                    }

                    trackBuilder.withValue(Tracks.TRACK_NAME, trackName);
                    final int color = Color.parseColor(getTrackColor(trackId));
                    trackBuilder.withValue(Tracks.TRACK_COLOR, color);
                    batch.add(trackBuilder.build());
                }

                if (newSession || sessionUpdated) {
                    builder.withValue(Sessions.TRACK_ID, trackId);
                }
            }

            if (session.has("speakers")) {
                final Uri speakerSessionsUri = Sessions.buildSpeakersDirUri(sessionId);
                final JSONArray speakers = session.getJSONArray("speakers");
                final HashSet<String> speakerIds = Sets.newHashSet();

                if (!isLocalSync()) {
                    final boolean sessionSpeakersUpdated = isSessionSpeakersUpdated(speakerSessionsUri,
                            speakers, resolver);
                    if (sessionSpeakersUpdated) {
                        Log.d(TAG, "Speakers of session with id " + sessionId + " was udpated.");
                        batch.add(ContentProviderOperation.newUpdate(sessionUri)
                                .withValue(Sessions.UPDATED, true).build());
                    }
                }

                for (int j = 0; j < speakers.length(); j++) {
                    JSONObject speaker = speakers.getJSONObject(j);

                    final Uri speakerUri = Uri.parse(speaker.getString("speakerUri"));
                    final String speakerId = speakerUri.getLastPathSegment();
                    speakerIds.add(speakerId);

                    batch.add(ContentProviderOperation.newInsert(speakerSessionsUri)
                            .withValue(SessionsSpeakers.SPEAKER_ID, speakerId)
                            .withValue(SessionsSpeakers.SESSION_ID, sessionId).build());
                }

                sessionSpeakerIds.put(sessionId, speakerIds);
            }

            if (session.has("tags")) {
                final Uri tagSessionsUri = Sessions.buildTagsDirUri(sessionId);
                final JSONArray tags = session.getJSONArray("tags");
                final HashSet<String> tagIds = Sets.newHashSet();

                for (int j = 0; j < tags.length(); j++) {
                    JSONObject tag = tags.getJSONObject(j);
                    final String tagName = tag.getString("name").toLowerCase();
                    final String tagId = Tags.generateTagId(tagName);
                    tagIds.add(tagId);

                    batch.add(ContentProviderOperation.newInsert(Tags.CONTENT_URI).withValue(Tags.TAG_ID, tagId)
                            .withValue(Tags.TAG_NAME, tagName).build());

                    batch.add(ContentProviderOperation.newInsert(SearchSuggest.CONTENT_URI)
                            .withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, tagName).build());

                    batch.add(ContentProviderOperation.newInsert(tagSessionsUri)
                            .withValue(SessionsTags.TAG_ID, tagId).withValue(SessionsTags.SESSION_ID, sessionId)
                            .build());
                }

                sessionTagIds.put(sessionId, tagIds);
            }
        }
    }

    if (isRemoteSync() && nrEntries > 0) {
        for (Entry<String, HashSet<String>> entry : sessionSpeakerIds.entrySet()) {
            String sessionId = entry.getKey();
            HashSet<String> speakerIds = entry.getValue();
            final Uri speakerSessionsUri = Sessions.buildSpeakersDirUri(sessionId);
            HashSet<String> lostSpeakerIds = getLostIds(speakerIds, speakerSessionsUri,
                    SpeakersQuery.PROJECTION, SpeakersQuery.SPEAKER_ID, resolver);
            for (String lostSpeakerId : lostSpeakerIds) {
                final Uri deleteUri = Sessions.buildSessionSpeakerUri(sessionId, lostSpeakerId);
                batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            }
        }

        for (Entry<String, HashSet<String>> entry : sessionTagIds.entrySet()) {
            String sessionId = entry.getKey();
            HashSet<String> tagIds = entry.getValue();
            final Uri tagSessionsUri = Sessions.buildTagsDirUri(sessionId);
            HashSet<String> lostTagIds = getLostIds(tagIds, tagSessionsUri, TagsQuery.PROJECTION,
                    TagsQuery.TAG_ID, resolver);
            for (String lostTagId : lostTagIds) {
                final Uri deleteUri = Sessions.buildSessionTagUri(sessionId, lostTagId);
                batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            }
        }

        HashSet<String> lostTrackIds = getLostIds(trackIds, Tracks.CONTENT_URI, TracksQuery.PROJECTION,
                TracksQuery.TRACK_ID, resolver);
        for (String lostTrackId : lostTrackIds) {
            Uri deleteUri = Tracks.buildSessionsUri(lostTrackId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Tracks.buildTrackUri(lostTrackId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        }
        HashSet<String> lostSessionIds = getLostIds(sessionIds, Sessions.CONTENT_URI, SessionsQuery.PROJECTION,
                SessionsQuery.SESSION_ID, resolver);
        for (String lostSessionId : lostSessionIds) {
            Uri deleteUri = Sessions.buildSpeakersDirUri(lostSessionId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Sessions.buildTagsDirUri(lostSessionId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Sessions.buildSessionUri(lostSessionId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        }
    }

    return batch;
}

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

private static void updateContactStatus(ArrayList<ContentProviderOperation> operationList, long rawContactId,
        String status) {//from www  . j  a  va  2 s. c om
    Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
    Uri entityUri = Uri.withAppendedPath(rawContactUri, Entity.CONTENT_DIRECTORY);
    Cursor c = mContentResolver.query(entityUri,
            new String[] { RawContacts.SOURCE_ID, Entity.DATA_ID, Entity.MIMETYPE, Entity.DATA1 }, null, null,
            null);
    try {
        while (c.moveToNext()) {
            if (!c.isNull(1)) {
                String mimeType = c.getString(2);

                if (mimeType.equals("vnd.android.cursor.item/vnd.org.c99.SyncProviderDemo.profile")) {
                    ContentProviderOperation.Builder builder = ContentProviderOperation
                            .newInsert(ContactsContract.StatusUpdates.CONTENT_URI);
                    builder.withValue(ContactsContract.StatusUpdates.DATA_ID, c.getLong(1));
                    builder.withValue(ContactsContract.StatusUpdates.STATUS, status);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_RES_PACKAGE,
                            "org.c99.SyncProviderDemo");
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_LABEL, R.string.app_name);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_ICON, R.drawable.logo);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_TIMESTAMP,
                            System.currentTimeMillis());
                    operationList.add(builder.build());

                    //Only change the text of our custom entry to the status message pre-Honeycomb, as the newer contacts app shows
                    //statuses elsewhere
                    if (Integer.decode(Build.VERSION.SDK) < 11) {
                        builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
                        builder.withSelection(BaseColumns._ID + " = '" + c.getLong(1) + "'", null);
                        builder.withValue(ContactsContract.Data.DATA3, status);
                        operationList.add(builder.build());
                    }
                }
            }
        }
    } finally {
        c.close();
    }
}

From source file:cz.maresmar.sfm.service.web.PortalsUpdateService.java

private static void updatePortals(@NonNull Context context) throws IOException, UnsupportedApiException {
    Timber.i("Portal data sync started");

    URL url = new URL(ServerContract.PORTALS_SERVER_ADDRESS);

    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    try (FirstLineInputStream fis = new FirstLineInputStream(urlConnection.getInputStream())) {

        SfmJsonPortalResponse response = parseEntries(ServerContract.REPLY_TYPE_PORTALS,
                SfmJsonPortalResponse.class, fis);

        ArrayList<ContentProviderOperation> operations = new ArrayList<>();
        Uri portalUri = ProviderContract.Portal.getUri();

        for (PortalEntry portalEntry : response.data) {
            operations.add(ContentProviderOperation.newInsert(portalUri)
                    .withValue(ProviderContract.Portal._ID, portalEntry.id)
                    .withValue(ProviderContract.Portal.PORTAL_GROUP_ID, portalEntry.pgid)
                    .withValue(ProviderContract.Portal.NAME, portalEntry.name)
                    .withValue(ProviderContract.Portal.PLUGIN, portalEntry.plugin)
                    .withValue(ProviderContract.Portal.REFERENCE, portalEntry.reference)
                    .withValue(ProviderContract.Portal.LOC_N, portalEntry.locN)
                    .withValue(ProviderContract.Portal.LOC_E, portalEntry.locE)
                    .withValue(ProviderContract.Portal.EXTRA, portalEntry.extra)
                    .withValue(ProviderContract.Portal.SECURITY, portalEntry.security)
                    .withValue(ProviderContract.Portal.FEATURES, portalEntry.features).withYieldAllowed(true)
                    .build());/*www .ja  v  a 2  s. c  o m*/
        }

        // Apply them once for performance boost
        try {
            context.getContentResolver().applyBatch(ProviderContract.AUTHORITY, operations);
        } catch (OperationApplicationException e) {
            Timber.e(e, "Cannot save elements to db");
            throw new UnsupportedOperationException("Cannot save elements to db ", e);
        } catch (RemoteException e) {
            Timber.e(e, "Cannot connect to db");
            throw new RuntimeException("Cannot connect to db", e);
        }
    } finally {
        urlConnection.disconnect();
    }
}

From source file:com.openerp.base.res.Res_PartnerSyncHelper.java

private void addContact(Context context, Account account, String partner_id, String name, String mail,
        String number, String mobile, String website, String street, String street2, String city, String zip,
        String company, String image) {

    ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
    int rawContactInsertIndex = operationList.size();

    ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);
    builder.withValue(RawContacts.ACCOUNT_NAME, account.name);
    builder.withValue(RawContacts.ACCOUNT_TYPE, account.type);
    builder.withValue(RawContacts.SYNC1, partner_id);
    operationList.add(builder.build());/* ww w  .  j av  a  2 s. c  om*/

    // Display Name
    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, name);
    operationList.add(builder.build());

    // Connection to send message from contact
    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.com.openerp.auth.profile");
    builder.withValue(ContactsContract.Data.DATA1, name);
    builder.withValue(ContactsContract.Data.DATA2, partner_id);
    builder.withValue(ContactsContract.Data.DATA3, "Send Message");
    operationList.add(builder.build());

    // Email
    if (!mail.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.Email.DATA, mail);
        operationList.add(builder.build());
    }

    // Phone number
    if (!number.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number);
        operationList.add(builder.build());
    }

    // Mobile number
    if (!mobile.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, mobile);
        builder.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
        operationList.add(builder.build());
    }

    // Website
    if (!website.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.Website.TYPE, website);
        operationList.add(builder.build());
    }

    // Address street 1
    if (!street.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredPostal.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, street);
        operationList.add(builder.build());
    }

    // Address street 2
    if (!street2.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredPostal.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, street2);
        operationList.add(builder.build());
    }

    // Address City
    if (!city.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredPostal.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, city);
        operationList.add(builder.build());
    }

    // Zip code
    if (!zip.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredPostal.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, zip);
        operationList.add(builder.build());
    }

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    // Partner Image
    if (!image.equals("false")) {

        Bitmap bitmapOrg = Base64Helper.getBitmapImage(context, image);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 100, stream);

        operationList.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, stream.toByteArray()).build());
    }

    // Organization
    if (!company.equals("false")) {
        operationList.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company)
                .withValue(ContactsContract.CommonDataKinds.Organization.TYPE,
                        ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
                .build());
    }

    try {
        mContentResolver.applyBatch(ContactsContract.AUTHORITY, operationList);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:cn.pjt.rxjava.contacts.ContactsFragment.java

/**
 * Accesses the Contacts content provider directly to insert a new contact.
 * <p>//from  w  w  w.  ja  v a  2s  .c  o m
 * The contact is called "__DUMMY ENTRY" and only contains a name.
 */
private void insertDummyContact() {
    // Two operations are needed to insert a new contact.
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(2);

    // First, set up a new raw contact.
    ContentProviderOperation.Builder op = ContentProviderOperation
            .newInsert(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null);
    operations.add(op.build());

    // Next, set the name for the contact.
    op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
            .withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, DUMMY_CONTACT_NAME);
    operations.add(op.build());

    // Apply the operations.
    ContentResolver resolver = getActivity().getContentResolver();
    try {
        resolver.applyBatch(ContactsContract.AUTHORITY, operations);
    } catch (RemoteException e) {
        Log.d(TAG, "Could not add a new contact: " + e.getMessage());
    } catch (OperationApplicationException e) {
        Log.d(TAG, "Could not add a new contact: " + e.getMessage());
    }
}

From source file:io.nuclei.box.Query.java

public ContentProviderOperation toInsertOperation(T object) {
    if (opType != QUERY_OPERATION_INSERT)
        throw new IllegalArgumentException("Not an insert query");
    if (contentValuesMapper == null)
        throw new IllegalArgumentException("Content Values Mapper is null");
    return ContentProviderOperation.newInsert(uri).withValues(contentValuesMapper.map(object)).build();
}