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:net.niyonkuru.koodroid.html.SubscribersHandler.java

@Override
public ArrayList<ContentProviderOperation> parse(Document doc, ContentResolver resolver)
        throws HandlerException {
    final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();

    Element subscriberLi = doc.select("div#banSelector li:has(div)").first();
    while (subscriberLi != null) {
        String text = subscriberLi.text();

        /* this assumes the name and phone number are separated by a space */
        int separator = text.lastIndexOf(' ') + 1;

        String subscriberId = text.substring(separator).replaceAll("\\D", "");
        if (subscriberId.length() != 10)
            throw new HandlerException(getString(R.string.parser_error_unexpected_input));

        final ContentProviderOperation.Builder builder;

        final Uri subscriberUri = Subscribers.buildSubscriberUri(subscriberId);
        if (subscriberExists(subscriberUri, resolver)) {
            builder = ContentProviderOperation.newUpdate(subscriberUri);
            builder.withValue(Subscribers.UPDATED, System.currentTimeMillis());
        } else {//w  w w .j av a 2  s.  c om
            builder = ContentProviderOperation.newInsert(Subscribers.CONTENT_URI);
        }
        builder.withValue(Subscribers.SUBSCRIBER_ID, subscriberId);

        String fullName = "";
        String[] names = text.substring(0, separator).split("\\s");
        for (String name : names) {
            fullName += ParserUtils.capitalize(name) + " ";
        }
        builder.withValue(Subscribers.SUBSCRIBER_FULL_NAME, fullName.trim());

        if (subscriberLi.hasAttr("onClick")) {
            String switchUrl = subscriberLi.attr("onClick");

            /* extract only the url */
            switchUrl = switchUrl.substring(switchUrl.indexOf('/'), switchUrl.lastIndexOf('\''));
            builder.withValue(Subscribers.SUBSCRIBER_SWITCHER, switchUrl);
        } else { /* this is the default subscriber as it doesn't have a switcher url */
            ContentValues cv = new ContentValues(1);
            cv.put(Settings.SUBSCRIBER, subscriberId);

            resolver.insert(Settings.CONTENT_URI, cv);
        }
        builder.withValue(Subscribers.SUBSCRIBER_EMAIL, mParent);

        batch.add(builder.build());

        subscriberLi = subscriberLi.nextElementSibling();
    }
    if (batch.size() == 0)
        throw new HandlerException(getString(R.string.parser_error_unexpected_input));

    JSONObject metadata = new JSONObject();
    try {
        metadata.put("subscribers", batch.size());
        metadata.put("language", getString(R.string.locale));
    } catch (JSONException ignored) {
    }
    Crittercism.setMetadata(metadata);
    Crittercism.setUsername(mParent);

    return batch;
}

From source file:org.xwalk.runtime.extension.api.contacts.ContactSaver.java

private Builder newInsertFieldBuilder(String mimeType) {
    String rawId = mUtils.getRawId(mId);
    if (rawId == null) {
        Log.e(TAG, "Failed to create builder to insert field of " + mId);
        return null;
    }/* w  w w .j av  a  2 s. c o m*/
    Builder builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
    builder.withValue(Data.RAW_CONTACT_ID, mUtils.getRawId(mId));
    builder.withValue(Data.MIMETYPE, mimeType);
    return builder;
}

From source file:com.manning.androidhacks.hack043.service.SQLContentProviderService.java

@Override
protected void onHandleIntent(Intent intent) {
    Builder builder = null;//from   ww  w .  j a  va  2 s .c o  m
    ContentResolver contentResolver = getContentResolver();
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    builder = ContentProviderOperation.newDelete(MySQLContentProvider.CONTENT_URI);
    operations.add(builder.build());

    for (int i = 1; i <= 100; i++) {
        ContentValues cv = new ContentValues();
        cv.put(MySQLContentProvider.COLUMN_TEXT, "" + i);

        builder = ContentProviderOperation.newInsert(MySQLContentProvider.CONTENT_URI);
        builder.withValues(cv);

        operations.add(builder.build());
    }

    try {
        contentResolver.applyBatch(MySQLContentProvider.AUTHORITY, operations);
    } catch (RemoteException e) {
        Log.e(TAG, "Couldn't apply batch: " + e.getMessage());
    } catch (OperationApplicationException e) {
        Log.e(TAG, "Couldn't apply batch: " + e.getMessage());
    }

}

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

@Override
public ArrayList<ContentProviderOperation> parse(ArrayList<JSONArray> entries, ContentResolver resolver)
        throws JSONException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
    final HashSet<String> speakerIds = new HashSet<String>();

    int nrEntries = 0;
    for (JSONArray speakers : entries) {
        Log.d(TAG, "Retrieved " + speakers.length() + " speaker entries.");
        nrEntries += speakers.length();//from  w w  w.j av  a2  s.c  om

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

            //              final String speakerId = sanitizeId(id);
            final Uri speakerUri = MixItContract.Speakers.buildSpeakerUri(id);
            speakerIds.add(id);

            boolean speakerUpdated = false;
            boolean newSpeaker = false;
            boolean build = false;
            ContentProviderOperation.Builder builder;
            if (isRowExisting(speakerUri, SpeakersQuery.PROJECTION, resolver)) {
                builder = ContentProviderOperation.newUpdate(speakerUri);
                speakerUpdated = isSpeakerUpdated(speakerUri, speaker, resolver);
            } else {
                newSpeaker = true;
                builder = ContentProviderOperation.newInsert(MixItContract.Speakers.CONTENT_URI);
                builder.withValue(MixItContract.Speakers.SPEAKER_ID, id);
                build = true;
            }

            if (newSpeaker || speakerUpdated) {
                builder.withValue(MixItContract.Speakers.LAST_NAME, speaker.getString("lastName"));
                builder.withValue(MixItContract.Speakers.FIRST_NAME, speaker.getString("firstName"));
                builder.withValue(MixItContract.Speakers.BIO, speaker.getString("bio"));
                builder.withValue(MixItContract.Speakers.LINKEDIN, speaker.getString("linkedin"));
                builder.withValue(MixItContract.Speakers.TWITTER, speaker.getString("twitter"));
                builder.withValue(MixItContract.Speakers.BLOG, speaker.getString("blog"));
                builder.withValue(MixItContract.Speakers.COMPANY, speaker.getString("company"));
                builder.withValue(MixItContract.Speakers.IMAGE_URL, speaker.getString("urlImage"));
                build = true;
            }
            if (build)
                batch.add(builder.build());
        }
    }

    // delete sessions with speakers deleted
    if (isRemoteSync() && nrEntries > 0) {
        for (String lostId : getLostIds(speakerIds, MixItContract.Speakers.CONTENT_URI,
                SpeakersQuery.PROJECTION, SpeakersQuery.SPEAKER_ID, resolver)) {
            Uri deleteUri = MixItContract.Speakers.buildSessionsDirUri(lostId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = MixItContract.Speakers.buildSpeakerUri(lostId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        }
    }

    return batch;
}

From source file:com.manning.androidhacks.hack043.service.BatchService.java

@Override
protected void onHandleIntent(Intent intent) {
    Builder builder = null;/*from w  w w. jav  a 2s  . c o m*/
    ContentResolver contentResolver = getContentResolver();
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    builder = ContentProviderOperation.newDelete(BatchNumbersContentProvider.CONTENT_URI);
    operations.add(builder.build());

    for (int i = 1; i <= 100; i++) {
        ContentValues cv = new ContentValues();
        cv.put(NoBatchNumbersContentProvider.COLUMN_TEXT, "" + i);

        builder = ContentProviderOperation.newInsert(BatchNumbersContentProvider.CONTENT_URI);
        builder.withValues(cv);

        operations.add(builder.build());
    }

    try {
        contentResolver.applyBatch(BatchNumbersContentProvider.AUTHORITY, operations);
    } catch (RemoteException e) {
        Log.e(TAG, "Couldn't apply batch: " + e.getMessage());
    } catch (OperationApplicationException e) {
        Log.e(TAG, "Couldn't apply batch: " + e.getMessage());
    }

}

From source file:fr.mixit.android.io.JsonHandlerApplyInterests.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  av a 2 s.  c  o  m

    final Uri itemUri = MixItContract.Interests.buildInterestUri(id);

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

    if (ProviderParsingUtils.isRowExisting(itemUri, MixItContract.Interests.PROJ.PROJECTION, resolver)) {
        builder = ContentProviderOperation.newUpdate(itemUri);
        itemUpdated = isItemUpdated(itemUri, item, resolver);
    } else {
        newItem = true;
        builder = ContentProviderOperation.newInsert(MixItContract.Interests.CONTENT_URI);
        builder.withValue(MixItContract.Interests.INTEREST_ID, id);
        build = true;
    }

    if (newItem || itemUpdated) {
        builder.withValue(MixItContract.Interests.NAME, item.getString(TAG_NAME));
        build = true;
    }
    if (build) {
        ProviderParsingUtils.addOpeAndApplyBatch(mAuthority, resolver, mBatch, false, builder.build());
    }

    return true;
}

From source file:ca.mudar.parkcatcher.io.PanelsCodesHandler.java

@Override
public ArrayList<ContentProviderOperation> parse(JSONTokener jsonTokener, ContentResolver resolver)
        throws JSONException, IOException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    ContentProviderOperation.Builder builderPanelsCodes;

    JSONObject jsonObject = new JSONObject(jsonTokener);

    final String status = jsonObject.getString(RemoteTags.STATUS);
    if (!RemoteValues.STATUS_OK.equals(status)) {
        return batch;
    }//w w w .  ja v a2  s .c o m

    final int nbPanelsCodes = jsonObject.getInt(RemoteTags.COUNT);
    // final int version = jsonObject.getInt(RemoteTags.VERSION);
    // final JSONArray columns =
    // jsonObject.getJSONArray(RemoteTags.COLUMNS);

    final JSONArray panelsCodes = jsonObject.getJSONArray(jsonObject.getString(RemoteTags.NAME));

    if ((panelsCodes.length() != nbPanelsCodes) || (nbPanelsCodes == 0)) {
        return batch;
    }

    jsonObject = null;

    for (int i = 0; i < nbPanelsCodes; i++) {
        final JSONArray panelCode = panelsCodes.getJSONArray(i);
        if (panelCode == null) {
            continue;
        }

        final int id = panelCode.getInt(0);
        final String code = panelCode.getString(1);
        final String desc = panelCode.getString(2);
        final int type = panelCode.getInt(3);

        builderPanelsCodes = ContentProviderOperation.newInsert(PanelsCodes.CONTENT_URI);

        builderPanelsCodes.withValue(PanelsCodes._ID, id);
        builderPanelsCodes.withValue(PanelsCodes.CODE, code);
        builderPanelsCodes.withValue(PanelsCodes.DESCRIPTION, desc);
        builderPanelsCodes.withValue(PanelsCodes.TYPE_DESC, type);

        batch.add(builderPanelsCodes.build());
    }

    return batch;
}

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

@Override
public ArrayList<ContentProviderOperation> parse(ArrayList<JSONArray> entries, ContentResolver resolver)
        throws JSONException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
    final HashSet<String> speakerIds = new HashSet<String>();

    int nrEntries = 0;
    for (JSONArray speakers : entries) {
        Log.d(TAG, "Retrieved " + speakers.length() + " speaker entries.");
        nrEntries += speakers.length();//from  w  ww.  j  a  v a2  s.c  o m

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

            final String speakerId = sanitizeId(id);
            final Uri speakerUri = Speakers.buildSpeakerUri(speakerId);
            speakerIds.add(speakerId);

            boolean speakerUpdated = false;
            boolean newSpeaker = false;
            boolean build = false;
            ContentProviderOperation.Builder builder;
            if (isRowExisting(Speakers.buildSpeakerUri(speakerId), SpeakersQuery.PROJECTION, resolver)) {
                builder = ContentProviderOperation.newUpdate(speakerUri);
                speakerUpdated = isSpeakerUpdated(speakerUri, speaker, resolver);
            } else {
                newSpeaker = true;
                builder = ContentProviderOperation.newInsert(Speakers.CONTENT_URI);
                builder.withValue(Speakers.SPEAKER_ID, speakerId);
                build = true;
            }

            if (newSpeaker || speakerUpdated) {
                builder.withValue(Speakers.FIRST_NAME, speaker.getString("firstName"));
                builder.withValue(Speakers.LAST_NAME, speaker.getString("lastName"));
                builder.withValue(Speakers.BIO, speaker.getString("bio"));
                builder.withValue(Speakers.COMPANY, speaker.getString("company"));
                builder.withValue(Speakers.IMAGE_URL, speaker.getString("imageURI"));
                build = true;
            }
            if (build)
                batch.add(builder.build());
        }
    }

    if (isRemoteSync() && nrEntries > 0) {
        for (String lostId : getLostIds(speakerIds, Speakers.CONTENT_URI, SpeakersQuery.PROJECTION,
                SpeakersQuery.SPEAKER_ID, resolver)) {
            Uri deleteUri = Speakers.buildSessionsDirUri(lostId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Speakers.buildSpeakerUri(lostId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        }
    }

    return batch;
}

From source file:com.goliathonline.android.kegbot.io.RemoteUserHandler.java

/** {@inheritDoc} */
@Override/*from  ww w. ja  va 2s  .  c  o  m*/
public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver)
        throws JSONException, IOException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    // Walk document, parsing any incoming entries
    if (!parser.has("result"))
        return batch;
    JSONObject result = parser.getJSONObject("result");
    JSONObject keg = result.getJSONObject("user");

    final String userId = sanitizeId(keg.getString("username"));
    final Uri userUri = Users.buildUserUri(userId);

    // Check for existing details, only update when changed
    final ContentValues values = queryUserDetails(userUri, resolver);
    final long localUpdated = values.getAsLong(SyncColumns.UPDATED);
    final long serverUpdated = 500; //entry.getUpdated();
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "found user " + userId);
        Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated);
    }

    // Clear any existing values for this session, treating the
    // incoming details as authoritative.
    batch.add(ContentProviderOperation.newDelete(userUri).build());

    final ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(Users.CONTENT_URI);

    builder.withValue(SyncColumns.UPDATED, serverUpdated);
    builder.withValue(Users.USER_ID, userId);

    if (keg.has("image")) {
        JSONObject image = keg.getJSONObject("image");
        if (image.has("url"))
            builder.withValue(Users.USER_IMAGE_URL, image.getString("url"));
    }

    // Normal session details ready, write to provider
    batch.add(builder.build());

    return batch;
}

From source file:at.bitfire.davdroid.resource.LocalGroup.java

@Override
public void clearDirty(String eTag) throws ContactsStorageException {
    assertID();/*from www . ja v a2  s. co m*/

    ContentValues values = new ContentValues(2);
    values.put(Groups.DIRTY, 0);
    values.put(COLUMN_ETAG, this.eTag = eTag);
    update(values);

    // update cached group memberships
    BatchOperation batch = new BatchOperation(addressBook.provider);

    // delete cached group memberships
    batch.enqueue(new BatchOperation.Operation(ContentProviderOperation
            .newDelete(addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI))
            .withSelection(CachedGroupMembership.MIMETYPE + "=? AND " + CachedGroupMembership.GROUP_ID + "=?",
                    new String[] { CachedGroupMembership.CONTENT_ITEM_TYPE, String.valueOf(id) })));

    // insert updated cached group memberships
    for (long member : getMembers())
        batch.enqueue(new BatchOperation.Operation(ContentProviderOperation
                .newInsert(addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI))
                .withValue(CachedGroupMembership.MIMETYPE, CachedGroupMembership.CONTENT_ITEM_TYPE)
                .withValue(CachedGroupMembership.RAW_CONTACT_ID, member)
                .withValue(CachedGroupMembership.GROUP_ID, id).withYieldAllowed(true)));

    batch.commit();
}