Example usage for android.content ContentResolver applyBatch

List of usage examples for android.content ContentResolver applyBatch

Introduction

In this page you can find the example usage for android.content ContentResolver applyBatch.

Prototype

public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
        @NonNull ArrayList<ContentProviderOperation> operations)
        throws RemoteException, OperationApplicationException 

Source Link

Document

Applies each of the ContentProviderOperation objects and returns an array of their results.

Usage

From source file:com.android.contacts.ContactSaveService.java

/**
 * Splits "diff" into subsets based on "MAX_CONTACTS_PROVIDER_BATCH_SIZE", applies each of the
 * subsets, adds the returned array to "results".
 *
 * @return the size of the array, if not null; -1 when the array is null.
 *///from  w w w. j a  v  a  2s .c o  m
private int applyDiffSubset(ArrayList<ContentProviderOperation> diff, int offset,
        ContentProviderResult[] results, ContentResolver resolver)
        throws RemoteException, OperationApplicationException {
    final int subsetCount = Math.min(diff.size() - offset, MAX_CONTACTS_PROVIDER_BATCH_SIZE);
    final ArrayList<ContentProviderOperation> subset = new ArrayList<>();
    subset.addAll(diff.subList(offset, offset + subsetCount));
    final ContentProviderResult[] subsetResult = resolver.applyBatch(ContactsContract.AUTHORITY, subset);
    if (subsetResult == null || (offset + subsetResult.length) > results.length) {
        return -1;
    }
    for (ContentProviderResult c : subsetResult) {
        results[offset++] = c;
    }
    return subsetResult.length;
}

From source file:de.ub0r.android.callmeter.data.RuleMatcher.java

/**
 * Match all unmatched logs./*from  ww  w  . j a v a  2 s .c  o m*/
 *
 * @param context    {@link Context}
 * @param showStatus post status to dialog/handler
 * @return true if a log was matched
 */
static synchronized boolean match(final Context context, final boolean showStatus) {
    Log.d(TAG, "match(ctx, ", showStatus, ")");
    long start = System.currentTimeMillis();
    boolean ret = false;
    load(context);
    final ContentResolver cr = context.getContentResolver();
    final Cursor cursor = cr.query(DataProvider.Logs.CONTENT_URI, DataProvider.Logs.PROJECTION,
            DataProvider.Logs.PLAN_ID + " = " + DataProvider.NO_ID, null, DataProvider.Logs.DATE + " ASC");
    if (cursor != null && cursor.moveToFirst()) {
        final int l = cursor.getCount();
        Handler h;
        if (showStatus) {
            h = Plans.getHandler();
            if (h != null) {
                final Message m = h.obtainMessage(Plans.MSG_BACKGROUND_PROGRESS_MATCHER);
                m.arg1 = 0;
                m.arg2 = l;
                m.sendToTarget();
            }
        }
        try {
            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            int i = 1;
            do {
                ret |= matchLog(cr, ops, cursor);
                if (i % PROGRESS_STEPS == 0 || (i < PROGRESS_STEPS && i % CallMeter.TEN == 0)) {
                    h = Plans.getHandler();
                    if (h != null) {
                        final Message m = h.obtainMessage(Plans.MSG_BACKGROUND_PROGRESS_MATCHER);
                        m.arg1 = i;
                        m.arg2 = l;
                        Log.d(TAG, "send progress: ", i, "/", l);
                        m.sendToTarget();
                    } else {
                        Log.d(TAG, "send progress: ", i, " handler=null");
                    }
                    Log.d(TAG, "save logs..");
                    cr.applyBatch(DataProvider.AUTHORITY, ops);
                    ops.clear();
                    Log.d(TAG, "sleeping..");
                    try {
                        Thread.sleep(CallMeter.MILLIS);
                    } catch (InterruptedException e) {
                        Log.e(TAG, "sleep interrupted", e);
                    }
                    Log.d(TAG, "sleep finished");
                }
                ++i;
            } while (cursor.moveToNext());
            if (ops.size() > 0) {
                cr.applyBatch(DataProvider.AUTHORITY, ops);
            }
        } catch (IllegalStateException e) {
            Log.e(TAG, "illegal state in RuleMatcher's loop", e);
        } catch (OperationApplicationException e) {
            Log.e(TAG, "illegal operation in RuleMatcher's loop", e);
        } catch (RemoteException e) {
            Log.e(TAG, "remote exception in RuleMatcher's loop", e);
        }
    }
    try {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
    } catch (IllegalStateException e) {
        Log.e(TAG, "illegal state while closing cursor", e);
    }

    if (ret) {
        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
        final boolean a80 = p.getBoolean(Preferences.PREFS_ALERT80, true);
        final boolean a100 = p.getBoolean(Preferences.PREFS_ALERT100, true);
        // check for alerts
        if ((a80 || a100) && plans != null && plans.size() > 0) {
            final long now = System.currentTimeMillis();
            int alert = 0;
            Plan alertPlan = null;
            int l = plans.size();
            for (int i = 0; i < l; i++) {
                final Plan plan = plans.valueAt(i);
                if (plan == null) {
                    continue;
                }
                if (plan.nextAlert > now) {
                    Log.d(TAG, "%s: skip alert until: %d now=%d", plan, plan.nextAlert, now);
                    continue;
                }
                int used = DataProvider.Plans.getUsed(plan.type, plan.limitType, plan.billedAmount,
                        plan.billedCost);
                int usedRate = plan.limit > 0 ? (int) ((used * CallMeter.HUNDRED) / plan.limit) : 0;
                if (a100 && usedRate >= CallMeter.HUNDRED) {
                    alert = usedRate;
                    alertPlan = plan;
                } else if (a80 && alert < CallMeter.EIGHTY && usedRate >= CallMeter.EIGHTY) {
                    alert = usedRate;
                    alertPlan = plan;
                }
            }
            if (alert > 0) {
                final NotificationManager mNotificationMgr = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                final String t = String.format(context.getString(R.string.alerts_message), alertPlan.name,
                        alert);
                NotificationCompat.Builder b = new NotificationCompat.Builder(context);
                b.setSmallIcon(android.R.drawable.stat_notify_error);
                b.setTicker(t);
                b.setWhen(now);
                b.setContentTitle(context.getString(R.string.alerts_title));
                b.setContentText(t);
                Intent i = new Intent(context, Plans.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                b.setContentIntent(PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT));
                mNotificationMgr.notify(0, b.build());
                // set nextAlert to beginning of next day
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DAY_OF_MONTH, 1);
                cal.set(Calendar.HOUR_OF_DAY, 0);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
                cal.set(Calendar.MILLISECOND, 0);
                alertPlan.nextAlert = cal.getTimeInMillis();
                final ContentValues cv = new ContentValues();
                cv.put(DataProvider.Plans.NEXT_ALERT, alertPlan.nextAlert);
                cr.update(DataProvider.Plans.CONTENT_URI, cv, DataProvider.Plans.ID + " = ?",
                        new String[] { String.valueOf(alertPlan.id) });
            }
        }
    }
    long end = System.currentTimeMillis();
    Log.i(TAG, "match(): ", end - start, "ms");
    return ret;
}

From source file:org.m2x.rssreader.service.FetcherService.java

private void downloadAllImages() {
    ContentResolver cr = MainApplication.getContext().getContentResolver();
    Cursor cursor = cr.query(TaskColumns.CONTENT_URI,
            new String[] { TaskColumns._ID, TaskColumns.ENTRY_ID, TaskColumns.IMG_URL_TO_DL,
                    TaskColumns.NUMBER_ATTEMPT },
            TaskColumns.IMG_URL_TO_DL + Constants.DB_IS_NOT_NULL, null, null);

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

    while (cursor.moveToNext()) {
        long taskId = cursor.getLong(0);
        long entryId = cursor.getLong(1);
        String imgPath = cursor.getString(2);
        int nbAttempt = 0;
        if (!cursor.isNull(3)) {
            nbAttempt = cursor.getInt(3);
        }/*from   w ww. j a  v a2 s  . c om*/

        try {
            NetworkUtils.downloadImage(entryId, imgPath);

            // If we are here, everything is OK
            operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            cr.notifyChange(EntryColumns.CONTENT_URI(entryId), null); // To refresh the view
        } catch (Exception e) {
            if (nbAttempt + 1 > MAX_TASK_ATTEMPT) {
                operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            } else {
                ContentValues values = new ContentValues();
                values.put(TaskColumns.NUMBER_ATTEMPT, nbAttempt + 1);
                operations.add(ContentProviderOperation.newUpdate(TaskColumns.CONTENT_URI(taskId))
                        .withValues(values).build());
            }
        }
    }

    cursor.close();

    if (!operations.isEmpty()) {
        try {
            cr.applyBatch(FeedData.AUTHORITY, operations);
        } catch (Throwable ignored) {
        }
    }
}

From source file:nl.privacybarometer.privacyvandaag.service.FetcherService.java

private void downloadAllImages() {
    ContentResolver cr = MainApplication.getContext().getContentResolver();
    Cursor cursor = cr.query(TaskColumns.CONTENT_URI,
            new String[] { TaskColumns._ID, TaskColumns.ENTRY_ID, TaskColumns.IMG_URL_TO_DL,
                    TaskColumns.NUMBER_ATTEMPT },
            TaskColumns.IMG_URL_TO_DL + Constants.DB_IS_NOT_NULL, null, null);

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

    while (cursor != null && cursor.moveToNext()) {
        long taskId = cursor.getLong(0);
        long entryId = cursor.getLong(1);
        String imgPath = cursor.getString(2);
        int nbAttempt = 0;
        if (!cursor.isNull(3)) {
            nbAttempt = cursor.getInt(3);
        }//from www.j  a v  a2  s. co  m

        try {
            NetworkUtils.downloadImage(entryId, imgPath);

            // If we are here, everything is OK
            operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
        } catch (Exception e) {
            if (nbAttempt + 1 > MAX_TASK_ATTEMPT) {
                operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            } else {
                ContentValues values = new ContentValues();
                values.put(TaskColumns.NUMBER_ATTEMPT, nbAttempt + 1);
                operations.add(ContentProviderOperation.newUpdate(TaskColumns.CONTENT_URI(taskId))
                        .withValues(values).build());
            }
        }
    }

    if (cursor != null)
        cursor.close();

    if (!operations.isEmpty()) {
        try {
            cr.applyBatch(FeedData.AUTHORITY, operations);
        } catch (Throwable ignored) {
        }
    }
}

From source file:de.kollode.redminebrowser.sync.SyncHelper.java

void performSync(SyncResult syncResult, Account account) throws IOException {

    NotificationManager mNotificationManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);

    android.support.v4.app.NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
    mBuilder.setContentTitle("Projects").setContentText("Syncing in progress")
            .setSmallIcon(R.drawable.ic_launcher);

    final ContentResolver resolver = mContext.getContentResolver();
    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);

    AccountManager accMgr = AccountManager.get(this.mContext);
    String serverUrl = accMgr.getUserData(account, "serverUrl");

    if (isOnline()) {

        final long startRemote = System.currentTimeMillis();

        int syncedProjects = 0;
        Log.i(sTag, "Remote syncing speakers");
        Log.i(sTag, serverUrl);/*from  w  ww . ja  v  a 2s .c  o m*/

        try {

            int offset = 0;
            int numberOfProjects;
            int limit = 100;
            boolean loadMore = true;

            do {
                String restQuery = "sort=updated_on:desc&limit=" + limit + "&offset=" + offset + "&key="
                        + accMgr.getPassword(account);

                Log.d(sTag, "REST URL: " + serverUrl + "/projects.json?" + restQuery);
                JSONObject projectsJson = getJsonFromUrl(serverUrl + "/projects.json?" + restQuery);

                numberOfProjects = projectsJson.getInt("total_count");
                mBuilder.setProgress(numberOfProjects, syncedProjects, false);
                mNotificationManager.notify(0, mBuilder.build());

                if (numberOfProjects < limit + offset) {
                    Log.d(sTag, "Enough Projects");
                    loadMore = false;
                } else {
                    Log.d(sTag, "More Projects");
                    offset += limit;
                }

                JSONArray projects = projectsJson.getJSONArray("projects");

                for (int i = 0; i < projects.length(); i++) {

                    JSONObject project = projects.getJSONObject(i);
                    Builder projectBuilder = ContentProviderOperation
                            .newInsert(Project.buildProjectsUri(account.name));

                    Log.d(sTag, project.toString());

                    try {
                        projectBuilder.withValue(Project.PARENT, project.getJSONObject("parent").getInt("id"));
                    } catch (Exception e) {

                    }

                    batch.add(projectBuilder.withValue(BaseColumns._ID, project.getInt("id"))
                            .withValue(Project.NAME, project.getString("name"))
                            .withValue(Project.IDENTIFIER, project.getString("identifier"))
                            .withValue(Project.UPDATED, System.currentTimeMillis())
                            .withValue(Project.CREATED, System.currentTimeMillis())
                            .withValue(Project.CREATED_ON, project.getString("created_on"))
                            .withValue(Project.UPDATED_ON, project.getString("updated_on")).build());

                    mBuilder.setProgress(numberOfProjects, syncedProjects++, false);
                    mNotificationManager.notify(0, mBuilder.build());
                }
            } while (loadMore && !this.isCanceled());

            try {
                // Apply all queued up batch operations for local data.
                resolver.applyBatch(RedmineTables.CONTENT_AUTHORITY, batch);
            } catch (RemoteException e) {
                throw new RuntimeException("Problem applying batch operation", e);
            } catch (OperationApplicationException e) {
                throw new RuntimeException("Problem applying batch operation", e);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (this.isCanceled()) {
            mBuilder.setContentText("Sync was canceled").setProgress(0, 0, false);
        } else {
            mBuilder.setContentText("Sync complete").setProgress(0, 0, false);
        }
        mNotificationManager.notify(0, mBuilder.build());

        syncResult.delayUntil = ((long) 60 * 60);

        Log.d(sTag, "Remote sync took " + (System.currentTimeMillis() - startRemote) + "ms");
        Log.d(sTag, "Number of projects: " + syncedProjects);
    }
}

From source file:com.android.contacts.ContactSaveService.java

private void addMembersToGroup(ContentResolver resolver, long[] rawContactsToAdd, long groupId) {
    if (rawContactsToAdd == null) {
        return;//w w  w . j  av  a  2 s. co  m
    }
    for (long rawContactId : rawContactsToAdd) {
        try {
            final ArrayList<ContentProviderOperation> rawContactOperations = new ArrayList<ContentProviderOperation>();

            // Build an assert operation to ensure the contact is not already in the group
            final ContentProviderOperation.Builder assertBuilder = ContentProviderOperation
                    .newAssertQuery(Data.CONTENT_URI);
            assertBuilder.withSelection(
                    Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "=? AND " + GroupMembership.GROUP_ROW_ID
                            + "=?",
                    new String[] { String.valueOf(rawContactId), GroupMembership.CONTENT_ITEM_TYPE,
                            String.valueOf(groupId) });
            assertBuilder.withExpectedCount(0);
            rawContactOperations.add(assertBuilder.build());

            // Build an insert operation to add the contact to the group
            final ContentProviderOperation.Builder insertBuilder = ContentProviderOperation
                    .newInsert(Data.CONTENT_URI);
            insertBuilder.withValue(Data.RAW_CONTACT_ID, rawContactId);
            insertBuilder.withValue(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
            insertBuilder.withValue(GroupMembership.GROUP_ROW_ID, groupId);
            rawContactOperations.add(insertBuilder.build());

            if (DEBUG) {
                for (ContentProviderOperation operation : rawContactOperations) {
                    Log.v(TAG, operation.toString());
                }
            }

            // Apply batch
            if (!rawContactOperations.isEmpty()) {
                resolver.applyBatch(ContactsContract.AUTHORITY, rawContactOperations);
            }
        } catch (RemoteException e) {
            // Something went wrong, bail without success
            FeedbackHelper.sendFeedback(this, TAG,
                    "Problem persisting user edits for raw contact ID " + String.valueOf(rawContactId), e);
        } catch (OperationApplicationException e) {
            // The assert could have failed because the contact is already in the group,
            // just continue to the next contact
            FeedbackHelper.sendFeedback(this, TAG, "Assert failed in adding raw contact ID "
                    + String.valueOf(rawContactId) + ". Already exists in group " + String.valueOf(groupId), e);
        }
    }
}

From source file:com.murrayc.galaxyzoo.app.QuestionFragment.java

/**
 * Avoid calling this from the main (UI) thread - StrictMode doesn't like it on at least API 15
 * and API 16./* w w  w .j  a  va2  s  .c  o  m*/
 *
 * @param classificationInProgress
 */
private void saveClassificationSync(final ClassificationInProgress classificationInProgress) {
    final String itemId = getItemId();
    if (TextUtils.equals(itemId, ItemsContentProvider.URI_PART_ITEM_ID_NEXT)) {
        Log.error("QuestionFragment.saveClassification(): Attempting to save with the 'next' ID.");
        return;
    }

    final Activity activity = getActivity();
    if (activity == null)
        return;

    final ContentResolver resolver = activity.getContentResolver();

    // Add the related Classification Answers:
    // Use a ContentProvider operation to perform operations together,
    // either completely or not at all, as a transaction.
    // This should prevent an incomplete classification from being uploaded
    // before we have finished adding it.
    //
    // We use the specific ArrayList<> subtype instead of List<> because
    // ContentResolver.applyBatch() takes an ArrayList for some reason.
    final ArrayList<ContentProviderOperation> ops = new ArrayList<>();

    int sequence = 0;
    final List<ClassificationInProgress.QuestionAnswer> answers = classificationInProgress.getAnswers();
    if (answers != null) {
        for (final ClassificationInProgress.QuestionAnswer answer : answers) {
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(ClassificationAnswer.CLASSIFICATION_ANSWERS_URI);
            final ContentValues valuesAnswers = new ContentValues();
            valuesAnswers.put(ClassificationAnswer.Columns.ITEM_ID, itemId);
            valuesAnswers.put(ClassificationAnswer.Columns.SEQUENCE, sequence);
            valuesAnswers.put(ClassificationAnswer.Columns.QUESTION_ID, answer.getQuestionId());
            valuesAnswers.put(ClassificationAnswer.Columns.ANSWER_ID, answer.getAnswerId());
            builder.withValues(valuesAnswers);
            ops.add(builder.build());

            //For instance, if the question has multiple-choice checkboxes to select before clicking
            //the "Done" answer:
            final List<String> checkboxIds = answer.getCheckboxIds();
            if (checkboxIds != null) {
                for (final String checkboxId : checkboxIds) {
                    builder = ContentProviderOperation
                            .newInsert(ClassificationCheckbox.CLASSIFICATION_CHECKBOXES_URI);
                    final ContentValues valuesCheckbox = new ContentValues();
                    valuesCheckbox.put(ClassificationCheckbox.Columns.ITEM_ID, itemId);
                    valuesCheckbox.put(ClassificationCheckbox.Columns.SEQUENCE, sequence);
                    valuesCheckbox.put(ClassificationCheckbox.Columns.QUESTION_ID, answer.getQuestionId());
                    valuesCheckbox.put(ClassificationCheckbox.Columns.CHECKBOX_ID, checkboxId);
                    builder.withValues(valuesCheckbox);
                    ops.add(builder.build());
                }
            }

            sequence++;
        }
    }

    //Mark the Item (Subject) as done:
    final Uri.Builder uriBuilder = Item.ITEMS_URI.buildUpon();
    uriBuilder.appendPath(getItemId());
    final ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(uriBuilder.build());
    final ContentValues values = new ContentValues();
    values.put(Item.Columns.DONE, true);
    values.put(Item.Columns.DATETIME_DONE, getCurrentDateTimeAsIso8601());
    values.put(Item.Columns.FAVORITE, classificationInProgress.isFavorite());
    builder.withValues(values);
    ops.add(builder.build());

    try {
        resolver.applyBatch(ClassificationAnswer.AUTHORITY, ops);
    } catch (final RemoteException | OperationApplicationException e) {
        //This should never happen, and would mean a loss of the current classification,
        //so let it crash the app and generate a report with a stacktrace,
        //because that's (slightly) better than just ignoring it.
        //
        //I guess that OperationApplicationException is not an unchecked exception,
        //because it could be caused by not just pure programmer error,
        //for instance if our data did not fulfill a Sqlite database constraint.
        Log.error("QuestionFragment. saveClassification(): Exception from applyBatch()", e);
        throw new RuntimeException("ContentResolver.applyBatch() failed.", e);
    }

    //The ItemsContentProvider will upload the classification later.
}

From source file:nl.privacybarometer.privacyvandaag.service.FetcherService.java

private void mobilizeAllEntries() {
    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(TaskColumns.CONTENT_URI,
            new String[] { TaskColumns._ID, TaskColumns.ENTRY_ID, TaskColumns.NUMBER_ATTEMPT },
            TaskColumns.IMG_URL_TO_DL + Constants.DB_IS_NULL, null, null);

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

    while (cursor != null && cursor.moveToNext()) {
        long taskId = cursor.getLong(0);
        long entryId = cursor.getLong(1);
        int nbAttempt = 0;
        if (!cursor.isNull(2)) {
            nbAttempt = cursor.getInt(2);
        }//  w  w w .  j  a  v a  2  s  .  c o m

        boolean success = false;

        Uri entryUri = EntryColumns.CONTENT_URI(entryId);
        Cursor entryCursor = cr.query(entryUri, null, null, null, null);

        if (entryCursor != null && entryCursor.moveToFirst()) {
            if (entryCursor.isNull(entryCursor.getColumnIndex(EntryColumns.MOBILIZED_HTML))) { // If we didn't already mobilized it
                int linkPos = entryCursor.getColumnIndex(EntryColumns.LINK);
                int abstractHtmlPos = entryCursor.getColumnIndex(EntryColumns.ABSTRACT);
                int feedIdPos = entryCursor.getColumnIndex(EntryColumns.FEED_ID);
                HttpURLConnection connection = null;

                try {
                    String link = entryCursor.getString(linkPos);
                    String feedId = entryCursor.getString(feedIdPos);
                    Cursor cursorFeed = cr.query(FeedColumns.CONTENT_URI(feedId), null, null, null, null);
                    cursorFeed.moveToNext();
                    int cookieNamePosition = cursorFeed.getColumnIndex(FeedColumns.COOKIE_NAME);
                    int cookieValuePosition = cursorFeed.getColumnIndex(FeedColumns.COOKIE_VALUE);
                    String cookieName = cursorFeed.getString(cookieNamePosition);
                    String cookieValue = cursorFeed.getString(cookieValuePosition);
                    cursorFeed.close();

                    // Take substring from RSS content and use it
                    // to try to find a text indicator for better content extraction
                    String contentIndicator = null;
                    String text = entryCursor.getString(abstractHtmlPos);
                    if (!TextUtils.isEmpty(text)) {
                        text = Html.fromHtml(text).toString();
                        if (text.length() > 60) {
                            contentIndicator = text.substring(20, 40);
                        }
                    }
                    connection = NetworkUtils.setupConnection(link, cookieName, cookieValue);
                    String mobilizedHtml = ArticleTextExtractor.extractContent(connection.getInputStream(),
                            contentIndicator);
                    if (mobilizedHtml != null) {
                        mobilizedHtml = HtmlUtils.improveHtmlContent(mobilizedHtml,
                                NetworkUtils.getBaseUrl(link));
                        ContentValues values = new ContentValues();
                        values.put(EntryColumns.MOBILIZED_HTML, mobilizedHtml);

                        ArrayList<String> imgUrlsToDownload = null;
                        if (NetworkUtils.needDownloadPictures()) {
                            imgUrlsToDownload = HtmlUtils.getImageURLs(mobilizedHtml);
                        }

                        String mainImgUrl;
                        if (imgUrlsToDownload != null) {
                            mainImgUrl = HtmlUtils.getMainImageURL(imgUrlsToDownload);
                        } else {
                            mainImgUrl = HtmlUtils.getMainImageURL(mobilizedHtml);
                        }

                        if (mainImgUrl != null) {
                            values.put(EntryColumns.IMAGE_URL, mainImgUrl);
                        }

                        if (cr.update(entryUri, values, null, null) > 0) {
                            success = true;
                            operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId))
                                    .build());
                            if (imgUrlsToDownload != null && !imgUrlsToDownload.isEmpty()) {
                                addImagesToDownload(String.valueOf(entryId), imgUrlsToDownload);
                            }
                        }
                    }
                } catch (Throwable ignored) {
                    if (connection != null) {
                        connection.disconnect();
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            } else { // We already mobilized it
                success = true;
                operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            }
        }
        if (entryCursor != null)
            entryCursor.close();

        if (!success) {
            if (nbAttempt + 1 > MAX_TASK_ATTEMPT) {
                operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            } else {
                ContentValues values = new ContentValues();
                values.put(TaskColumns.NUMBER_ATTEMPT, nbAttempt + 1);
                operations.add(ContentProviderOperation.newUpdate(TaskColumns.CONTENT_URI(taskId))
                        .withValues(values).build());
            }
        }
    }

    if (cursor != null)
        cursor.close();

    if (!operations.isEmpty()) {
        try {
            cr.applyBatch(FeedData.AUTHORITY, operations);
        } catch (Throwable ignored) {
        }
    }
}