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.goliathonline.android.kegbot.io.RemoteKegHandler.java

/** {@inheritDoc} */
@Override//from  w w  w  .  j  av a2  s.  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
    JSONObject result = parser.getJSONObject("result");
    JSONObject keg = result.getJSONObject("keg");
    JSONObject type = result.getJSONObject("type");
    JSONObject image = type.getJSONObject("image");

    final String kegId = sanitizeId(keg.getString("id"));
    final Uri kegUri = Kegs.buildKegUri(kegId);

    // Check for existing details, only update when changed
    final ContentValues values = queryKegDetails(kegUri, resolver);
    final long localUpdated = values.getAsLong(SyncColumns.UPDATED);
    final long serverUpdated = 500; //entry.getUpdated();
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "found keg " + kegId);
        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(kegUri).build());

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

    builder.withValue(SyncColumns.UPDATED, serverUpdated);
    builder.withValue(Kegs.KEG_ID, kegId);

    // Inherit starred value from previous row
    if (values.containsKey(Kegs.KEG_STARRED)) {
        builder.withValue(Kegs.KEG_STARRED, values.getAsInteger(Kegs.KEG_STARRED));
    }

    if (keg.has("status"))
        builder.withValue(Kegs.STATUS, keg.getString("status"));

    if (keg.has("volume_ml_remain"))
        builder.withValue(Kegs.VOLUME_REMAIN, keg.getDouble("volume_ml_remain"));

    if (keg.has("description"))
        builder.withValue(Kegs.DESCRIPTION, keg.getString("description"));

    if (keg.has("type_id"))
        builder.withValue(Kegs.TYPE_ID, keg.getString("type_id"));

    if (keg.has("size_id"))
        builder.withValue(Kegs.SIZE_ID, keg.getInt("size_id"));

    if (keg.has("percent_full"))
        builder.withValue(Kegs.PERCENT_FULL, keg.getDouble("percent_full"));

    if (keg.has("size_name"))
        builder.withValue(Kegs.SIZE_NAME, keg.getString("size_name"));

    if (keg.has("spilled_ml"))
        builder.withValue(Kegs.VOLUME_SPILL, keg.getDouble("spilled_ml"));

    if (keg.has("size_volume_ml"))
        builder.withValue(Kegs.VOLUME_SIZE, keg.getDouble("size_volume_ml"));

    if (type.has("name"))
        builder.withValue(Kegs.KEG_NAME, type.getString("name"));

    if (type.has("abv"))
        builder.withValue(Kegs.KEG_ABV, type.getDouble("abv"));

    if (image.has("url"))
        builder.withValue(Kegs.IMAGE_URL, image.getString("url"));

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

    return batch;
}

From source file:com.rukman.emde.smsgroups.platform.GMSContactOperations.java

public static long addGroupToContacts(Context context, ContentProviderClient provider, Account account,
        JSONObject group, SyncResult result)
        throws RemoteException, OperationApplicationException, JSONException {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ContentProviderOperation.Builder op = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
            .withValue(RawContacts.ACCOUNT_TYPE, GMSApplication.ACCOUNT_TYPE)
            .withValue(RawContacts.ACCOUNT_NAME, account.name)
            .withValue(RawContacts.SOURCE_ID, group.getString(JSONKeys.KEY_ID));
    ops.add(op.build());//w  ww . j  a v  a2 s .c  o  m
    op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(CommonDataKinds.StructuredName.DISPLAY_NAME, group.getString(JSONKeys.KEY_NAME));
    ops.add(op.build());
    op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(CommonDataKinds.Phone.NUMBER, group.get(JSONKeys.KEY_PHONE))
            .withValue(CommonDataKinds.Phone.TYPE, CommonDataKinds.Phone.TYPE_MAIN);
    ops.add(op.build());
    op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(Data.MIMETYPE, CommonDataKinds.Photo.CONTENT_ITEM_TYPE).withYieldAllowed(true);
    ops.add(op.build());
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    try {
        is = context.getAssets().open("gms.png", AssetManager.ACCESS_BUFFER);
        baos = new ByteArrayOutputStream();
        int value = is.read();
        while (value != -1) {
            baos.write(value);
            value = is.read();
        }
        op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, baos.toByteArray())
                .withYieldAllowed(true);
        ops.add(op.build());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (baos != null) {
                baos.close();
            }
        } catch (IOException ignore) {
        }
    }
    ContentProviderResult[] results = provider.applyBatch(ops);
    return (results[0].uri != null) ? ContentUris.parseId(results[0].uri) : -1L;
}

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

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

    ContentProviderOperation.Builder builderPanelsCodesRules;

    JSONObject jsonObject = new JSONObject(jsonTokener);

    final String status = jsonObject.optString(RemoteTags.STATUS);
    if (!RemoteValues.STATUS_OK.equals(status)) {
        return batch;
    }/*from w ww.  j  a va 2 s  . com*/

    final int nbPanelsCodesRules = jsonObject.optInt(RemoteTags.COUNT);
    // final int version = jsonObject.optInt(RemoteTags.VERSION);
    // final JSONArray columns =
    // jsonObject.optJSONArray(RemoteTags.COLUMNS);

    final JSONArray panelsCodesRules = jsonObject.optJSONArray(jsonObject.optString(RemoteTags.NAME));

    if ((panelsCodesRules.length() != nbPanelsCodesRules) || (nbPanelsCodesRules == 0)) {
        return batch;
    }

    jsonObject = null;

    for (int i = 0; i < nbPanelsCodesRules; i++) {
        final JSONArray panelCodeRule = panelsCodesRules.optJSONArray(i);
        if (panelCodeRule == null) {
            continue;
        }

        final int id = panelCodeRule.optInt(0);
        final int idPanelCode = panelCodeRule.optInt(1);
        final int minutesDuration = panelCodeRule.optInt(2);
        final int hourStart = panelCodeRule.optInt(3);
        final int hourEnd = panelCodeRule.optInt(4);
        final int hourDuration = panelCodeRule.optInt(5);
        final int dayStart = panelCodeRule.optInt(6);
        final int dayEnd = panelCodeRule.optInt(7);

        builderPanelsCodesRules = ContentProviderOperation.newInsert(PanelsCodesRules.CONTENT_URI);

        builderPanelsCodesRules.withValue(PanelsCodesRules._ID, id);
        builderPanelsCodesRules.withValue(PanelsCodesRules.ID_PANEL_CODE, idPanelCode);
        builderPanelsCodesRules.withValue(PanelsCodesRules.MINUTES_DURATION, minutesDuration);
        builderPanelsCodesRules.withValue(PanelsCodesRules.HOUR_START, hourStart);
        builderPanelsCodesRules.withValue(PanelsCodesRules.HOUR_END, hourEnd);
        builderPanelsCodesRules.withValue(PanelsCodesRules.HOUR_DURATION, hourDuration);
        builderPanelsCodesRules.withValue(PanelsCodesRules.DAY_START, dayStart);
        builderPanelsCodesRules.withValue(PanelsCodesRules.DAY_END, dayEnd);

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

    return batch;
}

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

private static void addContact(Account account, String name, String username) {
    Log.i(TAG, "Adding contact: " + name);
    ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();

    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, username);
    operationList.add(builder.build());/*w ww .  j  a  v a 2  s .  c om*/

    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());

    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.c99.SyncProviderDemo.profile");
    builder.withValue(ContactsContract.Data.DATA1, username);
    builder.withValue(ContactsContract.Data.DATA2, "SyncProviderDemo Profile");
    builder.withValue(ContactsContract.Data.DATA3, "View profile");
    operationList.add(builder.build());

    try {
        mContentResolver.applyBatch(ContactsContract.AUTHORITY, operationList);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:fr.mixit.android.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 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() + " session entries.");
        nrEntries += sessions.length();/*from w w  w .  j  a v  a  2  s. c  o m*/

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

            //               final String sessionId = sanitizeId(sessionId);
            final Uri sessionUri = MixItContract.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);
                sessionUpdated = isSessionUpdated(sessionUri, session, resolver);
            } else {
                newSession = true;
                builder = ContentProviderOperation.newInsert(MixItContract.Sessions.CONTENT_URI);
                builder.withValue(MixItContract.Sessions.SESSION_ID, sessionId);
            }

            if (newSession || sessionUpdated) {
                builder.withValue(MixItContract.Sessions.TITLE, session.getString("name"));
                if (session.has("room")) {
                    String room = session.getString("room");
                    if (room == null || room.length() == 0) {
                        room = "";
                    }
                    builder.withValue(MixItContract.Sessions.ROOM, room);
                }
                builder.withValue(MixItContract.Sessions.SUMMARY, session.getString("description"));

                if (session.has("track")) {
                    final String trackId = session.getString("track");
                    builder.withValue(MixItContract.Sessions.TRACK_ID, trackId);
                }

                if (session.has("slot")) {
                    final String trackId = session.getString("slot");
                    builder.withValue(MixItContract.Sessions.SLOT_ID, trackId);
                }

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

            if (session.has("speakers")) {
                final Uri speakerSessionsUri = MixItContract.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 sessionId " + sessionId + " was udpated.");

                        batch.add(ContentProviderOperation.newUpdate(sessionUri)
                                .withValue(MixItContract.Sessions.UPDATED, true).build());
                    }
                }

                for (int j = 0; j < speakers.length(); j++) {
                    /*                   JSONObject speaker = speakers.getJSONObject(j);
                                               
                                         final String speakerId = speaker.getString("speakerId");
                                         speakerIds.add(speakerId);*/

                    final String speakerId = speakers.getString(j);
                    speakerIds.add(speakerId);

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

                sessionSpeakerIds.put(sessionId, speakerIds);
            }

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

                if (!isLocalSync()) {
                    final boolean sessionTagsUpdated = isSessionTagsUpdated(tagSessionsUri, tags, resolver);
                    if (sessionTagsUpdated) {
                        Log.d(TAG, "Tags of session with sessionId " + sessionId + " was udpated.");
                        batch.add(ContentProviderOperation.newUpdate(sessionUri)
                                .withValue(MixItContract.Sessions.UPDATED, true).build());
                    }
                }

                for (int j = 0; j < tags.length(); j++) {
                    /*                   JSONObject tag = tags.getJSONObject(j);
                            
                                         final String tagId = tag.getString("tagId");
                                         tagIds.add(tagId);*/

                    final String tagId = tags.getString(j);
                    tagIds.add(tagId);

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

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

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

        HashSet<String> lostSessionIds = getLostIds(sessionIds, MixItContract.Sessions.CONTENT_URI,
                SessionsQuery.PROJECTION, SessionsQuery.SESSION_ID, resolver);
        for (String lostSessionId : lostSessionIds) {
            Uri deleteUri = MixItContract.Sessions.buildSpeakersDirUri(lostSessionId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = MixItContract.Sessions.buildSessionUri(lostSessionId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        }
    }

    return batch;
}

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

@Override
public ArrayList<ContentProviderOperation> parse(ArrayList<JSONArray> entries, ContentResolver resolver)
        throws JSONException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
    final HashMap<String, ContentProviderOperation> blockBatchMap = Maps.newHashMap();
    final HashMap<String, ContentProviderOperation> sessionUpdateBatchMap = Maps.newHashMap();

    int nrEntries = 0;
    for (JSONArray schedules : entries) {
        Log.d(TAG, "Retrieved " + schedules.length() + " schedule entries.");
        nrEntries += schedules.length();

        for (int i = 0; i < schedules.length(); i++) {
            JSONObject schedule = schedules.getJSONObject(i);

            final long startTime = ParserUtils.parseDevoxxTime(schedule.getString("fromTime"));
            final long endTime = ParserUtils.parseDevoxxTime(schedule.getString("toTime"));
            final String kind = schedule.getString("kind");

            final String blockId = Blocks.generateBlockId(kind, startTime, endTime);

            if (!blockBatchMap.containsKey(blockId)) {
                final Uri blockUri = Blocks.buildBlockUri(blockId);

                ContentProviderOperation.Builder builder;
                if (isRowExisting(Blocks.buildBlockUri(blockId), BlocksQuery.PROJECTION, resolver)) {
                    builder = ContentProviderOperation.newUpdate(blockUri);
                } else {
                    builder = ContentProviderOperation.newInsert(Blocks.CONTENT_URI);
                    builder.withValue(Blocks.BLOCK_ID, blockId);
                }//from w  w w .  j a  va  2s. co m
                builder.withValue(Blocks.BLOCK_START, startTime);
                builder.withValue(Blocks.BLOCK_END, endTime);

                final String type = schedule.getString("type");
                final String code = schedule.getString("code");

                if (code.startsWith("D10")) {
                    builder.withValue(Blocks.BLOCK_TITLE, type.replaceAll("\\ \\(.*\\)", ""));
                } else {
                    builder.withValue(Blocks.BLOCK_TITLE, schedule.getString("code"));
                }

                builder.withValue(Blocks.BLOCK_TYPE, kind);
                blockBatchMap.put(blockId, builder.build());
            }

            if (schedule.has("presentationUri")) {
                final Uri presentationUri = Uri.parse(schedule.getString("presentationUri"));
                final String sessionId = presentationUri.getLastPathSegment();
                final Uri sessionUri = Sessions.buildSessionUri(sessionId);

                if (isRowExisting(sessionUri, SessionsQuery.PROJECTION, resolver)) {
                    String roomId = null;
                    if (schedule.has("room")) {
                        final String roomName = schedule.getString("room");
                        Cursor cursor = resolver.query(Rooms.buildRoomsWithNameUri(roomName),
                                RoomsQuery.PROJECTION, null, null, null);
                        if (cursor.moveToNext()) {
                            roomId = cursor.getString(RoomsQuery.ROOM_ID);
                        }
                        cursor.close();
                    }
                    final ContentProviderOperation.Builder builder = ContentProviderOperation
                            .newUpdate(sessionUri);
                    builder.withValue(Sessions.BLOCK_ID, blockId);
                    builder.withValue(Sessions.ROOM_ID, roomId);
                    if (schedule.has("note")) {
                        final String note = schedule.getString("note");
                        if (note != null && note.trim().length() > 0) {
                            builder.withValue(Sessions.NOTE, note.trim());
                        }
                    }

                    sessionUpdateBatchMap.put(sessionId, builder.build());
                }
            }
        }
    }

    batch.addAll(blockBatchMap.values());
    batch.addAll(sessionUpdateBatchMap.values());

    if (isRemoteSync() && nrEntries > 0) {
        for (String lostId : getLostIds(blockBatchMap.keySet(), Blocks.CONTENT_URI, BlocksQuery.PROJECTION,
                BlocksQuery.BLOCK_ID, resolver)) {
            if (!lostId.startsWith("lab")) {
                final Uri lostBlockUri = Blocks.buildBlockUri(lostId);
                batch.add(ContentProviderOperation.newDelete(lostBlockUri).build());
            }
        }
        for (String lostId : getLostIds(sessionUpdateBatchMap.keySet(), Sessions.CONTENT_URI,
                SessionsQuery.PROJECTION, SessionsQuery.SESSION_ID, resolver)) {
            Uri deleteUri = Sessions.buildSpeakersDirUri(lostId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Sessions.buildTagsDirUri(lostId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Sessions.buildSessionUri(lostId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        }
    }

    return batch;
}

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

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

    if (parser.has("result")) {
        JSONObject events = parser.getJSONObject("result");
        JSONArray resultArray = events.getJSONArray("taps");
        int numKegs = resultArray.length();

        JSONObject taps;
        for (int i = 0; i < numKegs; i++) {
            taps = resultArray.getJSONObject(i);

            JSONObject keg = taps.getJSONObject("keg");
            JSONObject tap = taps.getJSONObject("tap");
            JSONObject beer = taps.getJSONObject("beer_type");
            JSONObject image = beer.getJSONObject("image");

            final String tapId = sanitizeId(tap.getString("id"));
            final Uri tapUri = Taps.buildTapUri(tapId);

            // Check for existing details, only update when changed
            final ContentValues values = queryTapDetails(tapUri, resolver);
            final long localUpdated = values.getAsLong(SyncColumns.UPDATED);
            final long serverUpdated = 500; //entry.getUpdated();
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "found tap " + tapId);
                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(tapUri).build());

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

            builder.withValue(SyncColumns.UPDATED, serverUpdated);
            builder.withValue(Taps.TAP_ID, tapId);

            if (tap.has("name"))
                builder.withValue(Taps.TAP_NAME, tap.getString("name"));

            if (tap.has("current_keg_id"))
                builder.withValue(Taps.KEG_ID, tap.getDouble("current_keg_id"));

            if (keg.has("status"))
                builder.withValue(Taps.STATUS, keg.getString("status"));

            if (keg.has("percent_full"))
                builder.withValue(Taps.PERCENT_FULL, keg.getString("percent_full"));

            if (keg.has("size_name"))
                builder.withValue(Taps.SIZE_NAME, keg.getString("size_name"));

            if (keg.has("volume_ml_remain"))
                builder.withValue(Taps.VOL_REMAIN, keg.getDouble("volume_ml_remain"));

            if (keg.has("size_volume_ml"))
                builder.withValue(Taps.VOL_SIZE, keg.getDouble("size_volume_ml"));

            if (beer.has("name"))
                builder.withValue(Taps.BEER_NAME, beer.getString("name"));

            if (keg.has("description"))
                builder.withValue(Taps.DESCRIPTION, keg.getString("description"));

            JSONObject last_temp = tap.getJSONObject("last_temperature");

            if (last_temp.has("temperature_c"))
                builder.withValue(Taps.LAST_TEMP, last_temp.getString("temperature_c"));

            if (last_temp.has("record_time"))
                builder.withValue(Taps.LAST_TEMP_TIME, last_temp.getString("record_time"));

            if (image.has("url"))
                builder.withValue(Taps.IMAGE_URL, image.getString("url"));

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

    return batch;
}

From source file:com.conferenceengineer.android.iosched.io.SpeakersHandler.java

private ArrayList<ContentProviderOperation> buildContentProviderOperations(PresentersResponse presenters) {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
    if (presenters != null) {
        List<PresenterResponse> presenterList = presenters.getPresenters();
        int numSpeakers = presenterList.size();

        if (numSpeakers > 0) {
            LOGI(TAG, "Updating presenters data");

            // Clear out existing speakers
            batch.add(ContentProviderOperation
                    .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(Speakers.CONTENT_URI)).build());

            // Insert latest speaker data
            for (PresenterResponse presenter : presenterList) {
                // Hack: Fix speaker URL so that it's not being resized
                // Depends on thumbnail URL being exactly in the format we want
                String thumbnail = presenter.getThumbnailUrl();
                if (thumbnail != null) {
                    thumbnail = thumbnail.replace("?sz=50", "?sz=100");
                }//from  w  w  w . ja  v a  2 s  .  com

                batch.add(ContentProviderOperation
                        .newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(Speakers.CONTENT_URI))
                        .withValue(SyncColumns.UPDATED, System.currentTimeMillis())
                        .withValue(Speakers.SPEAKER_ID, presenter.getId())
                        .withValue(Speakers.SPEAKER_NAME, presenter.getName())
                        .withValue(Speakers.SPEAKER_ABSTRACT, presenter.getBio())
                        .withValue(Speakers.SPEAKER_IMAGE_URL, thumbnail)
                        .withValue(Speakers.SPEAKER_URL, presenter.getPlusoneUrl()).build());
            }
        }

    }
    return batch;
}

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

public static Integer refreshAlbums() {
    try {// w ww .  j  a  va 2 s.co  m
        JSONArray json = ApiHelper.callApiForArray("albums");
        ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(
                json.length() + 1);

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

        for (int i = 0; i < json.length(); ++i) {
            JSONObject o = json.getJSONObject(i);

            operations.add(ContentProviderOperation.newInsert(MuckeboxProvider.URI_ALBUMS)
                    .withValue(AlbumEntry.SHORT_ID, o.getInt("id"))
                    .withValue(AlbumEntry.SHORT_TITLE, o.getString("title"))
                    .withValue(AlbumEntry.SHORT_ARTIST_ID, o.getInt("artist_id"))
                    .withValue(AlbumEntry.SHORT_CREATED, o.getInt("created")).build());
        }

        Muckebox.getAppContext().getContentResolver().applyBatch(MuckeboxProvider.AUTHORITY, operations);

        Log.d(LOG_TAG, "Got " + json.length() + " albums");
    } 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_albums;
    } catch (JSONException e) {
        return R.string.error_json;
    } catch (RemoteException e) {
        e.printStackTrace();
        return R.string.error_reload_albums;
    } catch (OperationApplicationException e) {
        e.printStackTrace();
        return R.string.error_reload_albums;
    }

    return null;
}

From source file:com.digipom.manteresting.android.processor.json.NailsJsonProcessor.java

@Override
public ArrayList<ContentProviderOperation> parse(JSONObject response, Meta meta) throws JSONException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
    final TreeSet<Integer> nailIds = new TreeSet<Integer>();
    final Cursor nails = resolver.query(ManterestingContract.Nails.CONTENT_URI, new String[] { Nails.NAIL_ID },
            null, null, Nails.NAIL_ID + " DESC");
    int greatestOfExisting = Integer.MIN_VALUE;

    if (nails != null && !nails.isClosed()) {
        try {//w  ww.  j  a va2s.c o  m
            nails.moveToFirst();

            final int idColumn = nails.getColumnIndex(Nails.NAIL_ID);

            while (!nails.isAfterLast()) {
                final int nailId = nails.getInt(idColumn);
                nailIds.add(nailId);
                greatestOfExisting = nailId > greatestOfExisting ? nailId : greatestOfExisting;
                nails.moveToNext();
            }
        } finally {
            if (nails != null) {
                nails.close();
            }
        }
    }

    final JSONArray objects = response.getJSONArray("objects");
    int smallestOfNew = Integer.MAX_VALUE;

    for (int i = 0; i < objects.length(); i++) {
        final JSONObject nailObject = objects.getJSONObject(i);

        final boolean isPrivate = nailObject.getJSONObject("workbench").getBoolean("private");

        if (!isPrivate) {
            final ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(Nails.CONTENT_URI);
            final int nailId = nailObject.getInt("id");
            smallestOfNew = nailId < smallestOfNew ? nailId : smallestOfNew;

            builder.withValue(Nails.NAIL_ID, nailId);
            builder.withValue(Nails.NAIL_JSON, nailObject.toString());

            batch.add(builder.build());
            nailIds.add(nailId);
        }
    }

    // If more than LIMIT were fetched, and this was the initial fetch, then
    // we flush everything in the DB before adding the new nails (as
    // otherwise we would introduce a gap).
    if (meta.nextOffset == meta.nextLimit // For initial fetch
            && smallestOfNew > greatestOfExisting) {
        if (LoggerConfig.canLog(Log.DEBUG)) {
            Log.d(TAG, "Flushing all existing nails on initial fetch, so as to avoid a gap.");
        }

        resolver.delete(Nails.CONTENT_URI, null, null);
    } else {
        // If more than 500 nails, find the 500th biggest and delete those
        // after it.
        if (nailIds.size() > MAX_COUNT) {
            Iterator<Integer> it = nailIds.descendingIterator();

            for (int i = 0; i < MAX_COUNT; i++) {
                it.next();
            }

            final Integer toDelete = it.next();

            if (LoggerConfig.canLog(Log.DEBUG)) {
                Log.d(TAG, "deleting from nails where NAIL_ID is less than or equal to " + toDelete);
            }

            SelectionBuilder selectionBuilder = new SelectionBuilder();
            selectionBuilder.where(ManterestingContract.Nails.NAIL_ID + " <= ?",
                    new String[] { String.valueOf(toDelete) });
            resolver.delete(ManterestingContract.Nails.CONTENT_URI, selectionBuilder.getSelection(),
                    selectionBuilder.getSelectionArgs());
        }
    }

    return batch;
}