Example usage for android.content ContentProviderOperation newDelete

List of usage examples for android.content ContentProviderOperation newDelete

Introduction

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

Prototype

public static Builder newDelete(Uri uri) 

Source Link

Document

Create a Builder suitable for building a delete ContentProviderOperation .

Usage

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");
                }/* ww w . j ava  2s  .  co  m*/

                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:net.peterkuterna.android.apps.devoxxsched.io.RemoteRoomsHandler.java

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

    int nrEntries = 0;
    for (JSONArray rooms : entries) {
        Log.d(TAG, "Retrieved " + rooms.length() + " room entries.");
        nrEntries += rooms.length();//from   ww w.  j  av a2s.  co m

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

            final String roomId = sanitizeId(id);
            final Uri roomUri = Rooms.buildRoomUri(roomId);
            roomIds.add(roomId);

            ContentProviderOperation.Builder builder;
            if (isRowExisting(Rooms.buildRoomUri(roomId), RoomsQuery.PROJECTION, resolver)) {
                builder = ContentProviderOperation.newUpdate(roomUri);
            } else {
                builder = ContentProviderOperation.newInsert(Rooms.CONTENT_URI);
                builder.withValue(Rooms.ROOM_ID, roomId);
            }
            builder.withValue(Rooms.NAME, room.getString("name"));
            builder.withValue(Rooms.CAPACITY, room.getString("capacity"));
            batch.add(builder.build());
        }
    }

    if (isRemoteSync() && nrEntries > 0) {
        for (String lostId : getLostIds(roomIds, Rooms.CONTENT_URI, RoomsQuery.PROJECTION, RoomsQuery.ROOM_ID,
                resolver)) {
            final Uri lostRoomUri = Rooms.buildRoomUri(lostId);
            batch.add(ContentProviderOperation.newDelete(lostRoomUri).build());
        }
    }

    return batch;
}

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

/** {@inheritDoc} */
@Override//w w  w. j  a  v  a  2 s  . c o 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.google.samples.apps.iosched.io.SessionsHandler.java

@Override
public void makeContentProviderOperations(ArrayList<ContentProviderOperation> list) {
    Uri uri = ScheduleContractHelper.setUriAsCalledFromSyncAdapter(ScheduleContract.Sessions.CONTENT_URI);

    // build a map of session to session import hashcode so we know what to update,
    // what to insert, and what to delete
    HashMap<String, String> sessionHashCodes = loadSessionHashCodes();
    boolean incrementalUpdate = (sessionHashCodes != null) && (sessionHashCodes.size() > 0);

    // set of sessions that we want to keep after the sync
    HashSet<String> sessionsToKeep = new HashSet<String>();

    if (incrementalUpdate) {
        LOGD(TAG, "Doing incremental update for sessions.");
    } else {/*from  w  ww . j a va  2 s. co  m*/
        LOGD(TAG, "Doing full (non-incremental) update for sessions.");
        list.add(ContentProviderOperation.newDelete(uri).build());
    }

    int updatedSessions = 0;
    for (Session session : mSessions.values()) {
        // Set the session grouping order in the object, so it can be used in hash calculation
        session.groupingOrder = computeTypeOrder(session);

        // compute the incoming session's hashcode to figure out if we need to update
        String hashCode = session.getImportHashCode();
        sessionsToKeep.add(session.id);

        // add session, if necessary
        if (!incrementalUpdate || !sessionHashCodes.containsKey(session.id)
                || !sessionHashCodes.get(session.id).equals(hashCode)) {
            ++updatedSessions;
            boolean isNew = !incrementalUpdate || !sessionHashCodes.containsKey(session.id);
            buildSession(isNew, session, list);

            // add relationships to speakers and track
            buildSessionSpeakerMapping(session, list);
            buildTagsMapping(session, list);
        }
    }

    int deletedSessions = 0;
    if (incrementalUpdate) {
        for (String sessionId : sessionHashCodes.keySet()) {
            if (!sessionsToKeep.contains(sessionId)) {
                buildDeleteOperation(sessionId, list);
                ++deletedSessions;
            }
        }
    }

    LOGD(TAG, "Sessions: " + (incrementalUpdate ? "INCREMENTAL" : "FULL") + " update. " + updatedSessions
            + " to update, " + deletedSessions + " to delete. New total: " + mSessions.size());
}

From source file:pl.epodreczniki.service.MetadataService.java

@Override
protected void onHandleIntent(Intent intent) {
    try {//from   w ww. j av a2 s.  c o  m
        Log.e("MS", "getting data");
        changeStatus(true);
        final String jsonData = TransferHelper.getMetaData();
        final Collection<JSONBook> books = parseBooks(jsonData);
        final ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
        for (JSONBook b : books) {
            operations.addAll(processBook(b));
        }
        if (operations.size() > 0) {
            getContentResolver().applyBatch(BooksProvider.AUTHORITY, operations);
        }

        Set<String> mdContentIdFromJson = new HashSet<String>();
        for (JSONBook b : books) {
            mdContentIdFromJson.add(b.getMdContentId());
        }
        ArrayList<ContentProviderOperation> delCpos = new ArrayList<ContentProviderOperation>();
        Cursor c = getContentResolver().query(BooksProvider.BOOKS_URI,
                new String[] { BooksTable.C_MD_CONTENT_ID, BooksTable.C_STATUS }, null, null, null);
        if (c != null) {
            while (c.moveToNext()) {
                String mdContentId = c.getString(0);
                BookStatus bs = BookStatus.fromInteger(c.getInt(1));
                if (bs == BookStatus.REMOTE && !mdContentIdFromJson.contains(mdContentId)) {
                    delCpos.add(ContentProviderOperation.newDelete(Util.getUriForBooks(mdContentId)).build());
                }
            }
            c.close();
        }
        if (delCpos.size() > 0) {
            getContentResolver().applyBatch(BooksProvider.AUTHORITY, delCpos);
        }
    } catch (Exception e) {
        showToast(R.string.ms_toast_downloadingBookFailed, Toast.LENGTH_LONG);
        Log.e("GET DATA", e.toString());
    } finally {
        changeStatus(false);
        requestCovers();
        ConnectionDetector.checkDb(this);
    }
}

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

public static Integer refreshAlbums() {
    try {//from w  w w  . ja  v  a2s  .com
        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.nononsenseapps.feeder.model.RssSyncHelper.java

/**
 * Synchronize pending updates//  www. j  av  a 2s  .c o  m
 *
 * @param context
 * @param operations deletes will be added to operations
 */
public static void syncPending(final Context context, final String token,
        final ArrayList<ContentProviderOperation> operations) {
    if (token == null) {
        throw new NullPointerException("Token was null");
    }

    Cursor c = null;
    try {
        c = context.getContentResolver().query(PendingNetworkSQL.URI, PendingNetworkSQL.FIELDS, null, null,
                null);

        while (c != null && c.moveToNext()) {
            PendingNetworkSQL pending = new PendingNetworkSQL(c);
            boolean success = false;

            if (pending.isDelete()) {
                try {
                    // catch 404 special
                    deleteFeed(context, token, pending.url);
                    success = true;
                } catch (RetrofitError e) {
                    if (e.getResponse() != null && e.getResponse().getStatus() == 404) {
                        // 404 is fine, already deleted
                        success = true;
                    } else {
                        // Not OK, throw it
                        throw e;
                    }

                }
            } else if (pending.isPut()) {
                putFeed(context, token, pending.title, pending.url, pending.tag);
                success = true;
            }

            if (success) {
                // Remove from db
                operations.add(ContentProviderOperation
                        .newDelete(Uri.withAppendedPath(PendingNetworkSQL.URI, Long.toString(pending.id)))
                        .build());
            }
        }

    } finally {
        if (c != null) {
            c.close();
        }
    }
}

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

/** {@inheritDoc} */
@Override//  w  w  w . ja v  a 2 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
    int drink_id = 0;
    JSONObject result = parser.getJSONObject("result");
    JSONArray drinks = result.getJSONArray("drinks");
    JSONObject drink;
    for (int i = 0; i < drinks.length(); i++) {
        if (drink_id == 0) { // && ENTRY.equals(parser.getName()
            // Process single spreadsheet row at a time
            drink = drinks.getJSONObject(i);
            final String drinkId = sanitizeId(drink.getString("id"));
            final Uri drinkUri = Drinks.buildDrinkUri(drinkId);

            // Check for existing details, only update when changed
            final ContentValues values = queryDrinkDetails(drinkUri, resolver);
            final long localUpdated = values.getAsLong(SyncColumns.UPDATED);
            final long serverUpdated = 500; //entry.getUpdated();
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "found drink " + drinkId);
                Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated);
            }
            if (localUpdated != KegbotContract.UPDATED_NEVER)
                continue;

            final Uri drinkKegUri = Drinks.buildKegUri(drinkId);
            final Uri drinkUserUri = Drinks.buildUserUri(drinkId);

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

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

            builder.withValue(SyncColumns.UPDATED, serverUpdated);
            builder.withValue(Drinks.DRINK_ID, drinkId);

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

            if (drink.has("session_id"))
                builder.withValue(Drinks.SESSION_ID, drink.getInt("session_id"));
            if (drink.has("status"))
                builder.withValue(Drinks.STATUS, drink.getString("status"));
            if (drink.has("user_id"))
                builder.withValue(Drinks.USER_ID, drink.getString("user_id"));
            if (drink.has("keg_id"))
                builder.withValue(Drinks.KEG_ID, drink.getInt("keg_id"));
            if (drink.has("volume_ml"))
                builder.withValue(Drinks.VOLUME, drink.getDouble("volume_ml"));
            if (drink.has("pour_time"))
                builder.withValue(Drinks.POUR_TIME, drink.getString("pour_time"));

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

            // Assign kegs
            final int kegId = drink.getInt("keg_id");
            batch.add(ContentProviderOperation.newInsert(drinkKegUri).withValue(DrinksKeg.DRINK_ID, drinkId)
                    .withValue(DrinksKeg.KEG_ID, kegId).build());

            // Assign users
            if (drink.has("user_id")) {
                final String userId = drink.getString("user_id");
                batch.add(ContentProviderOperation.newInsert(drinkUserUri)
                        .withValue(DrinksUser.DRINK_ID, drinkId).withValue(DrinksUser.USER_ID, userId).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();/* w  ww . j a  v  a2 s .  com*/

        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: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 ww  . j a v  a2 s.  com

        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;
}