Example usage for android.database Cursor moveToNext

List of usage examples for android.database Cursor moveToNext

Introduction

In this page you can find the example usage for android.database Cursor moveToNext.

Prototype

boolean moveToNext();

Source Link

Document

Move the cursor to the next row.

Usage

From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferDBUtil.java

/**
 * Queries all the PartETags of completed parts from the multipart upload
 * specified by the mainUploadId. The list of PartETags is used to complete
 * a multiart upload, so it's usually called after all partUpload tasks are
 * finished.// w  w  w  .  j  a  v a 2 s.  co m
 *
 * @param mainUploadId The mainUploadId of a multipart upload task
 * @return A list of PartEtag of completed parts
 */
public List<PartETag> queryPartETagsOfUpload(int mainUploadId) {
    final List<PartETag> partETags = new ArrayList<PartETag>();
    Cursor c = null;
    int partNum = 0;
    String eTag = null;
    try {
        c = transferDBBase.query(getPartUri(mainUploadId), null, null, null, null);
        while (c.moveToNext()) {
            partNum = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_PART_NUM));
            eTag = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_ETAG));
            partETags.add(new PartETag(partNum, eTag));
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return partETags;
}

From source file:com.eTilbudsavis.etasdk.DbHelper.java

/**
 * /*from   w  w w.ja v  a  2  s. c  om*/
 * @param sl
 * @param userId
 * @param includeDeleted
 * @return
 */
public List<Share> getShares(Shoppinglist sl, User user, boolean includeDeleted) {
    String slId = escape(sl.getId());
    String q = null;
    if (includeDeleted) {
        q = String.format("SELECT * FROM %s WHERE %s=%s AND %s=%s", SHARE_TABLE, SHOPPINGLIST_ID, slId, USER,
                user.getUserId());
    } else {
        q = String.format("SELECT * FROM %s WHERE %s=%s AND %s!=%s AND %s=%s", SHARE_TABLE, SHOPPINGLIST_ID,
                slId, STATE, SyncState.DELETE, USER, user.getUserId());
    }

    List<Share> shares = new ArrayList<Share>();
    Cursor c = null;
    try {
        c = execQuery(q);
        if (c.moveToFirst()) {
            do {
                shares.add(cursorToShare(c, sl));
            } while (c.moveToNext());
        }
    } catch (IllegalStateException e) {
        EtaLog.d(TAG, e.getMessage(), e);
    } finally {
        closeCursorAndDB(c);
    }

    return shares;
}

From source file:com.wildplot.android.ankistats.AnswerButton.java

public boolean calculateAnswerButtons(int type) {
    mTitle = R.string.stats_answer_buttons;
    mAxisTitles = new int[] { R.string.stats_answer_type, R.string.stats_answers,
            R.string.stats_cumulative_correct_percentage };

    mValueLabels = new int[] { R.string.statistics_learn, R.string.statistics_young,
            R.string.statistics_mature };
    mColors = new int[] { R.color.stats_learn, R.color.stats_young, R.color.stats_mature };

    mType = type;//from   www  .  j  a  v a2s.  co m
    String lim = _revlogLimitWholeOnly().replaceAll("[\\[\\]]", "");

    String lims = ""; //TODO when non whole collection selection is possible test this!
    int days = 0;

    if (lim.length() > 0)
        lims += lim + " and ";

    if (type == Utils.TYPE_MONTH)
        days = 30;
    else if (type == Utils.TYPE_YEAR)
        days = 365;
    else
        days = -1;

    if (days > 0)
        lims += "id > " + ((mCollectionData.getDayCutoff() - (days * 86400)) * 1000);
    if (lims.length() > 0)
        lim = "where " + lims;
    else
        lim = "";

    ArrayList<double[]> list = new ArrayList<double[]>();
    Cursor cur = null;
    String query = "select (case " + "                when type in (0,2) then 0 "
            + "        when lastIvl < 21 then 1 " + "        else 2 end) as thetype, "
            + "        (case when type in (0,2) and ease = 4 then 3 else ease end), count() from revlog " + lim
            + " " + "        group by thetype, ease " + "        order by thetype, ease";

    try {
        cur = mAnkiDb.getDatabase().rawQuery(query, null);
        while (cur.moveToNext()) {
            list.add(new double[] { cur.getDouble(0), cur.getDouble(1), cur.getDouble(2) });
        }

    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }

    //TODO adjust for AnswerButton, for now only copied from intervals
    // small adjustment for a proper chartbuilding with achartengine
    //        if (list.size() == 0 || list.get(0)[0] > 0) {
    //            list.add(0, new double[] { 0, 0, 0 });
    //        }
    //        if (num == -1 && list.size() < 2) {
    //            num = 31;
    //        }
    //        if (type != Utils.TYPE_LIFE && list.get(list.size() - 1)[0] < num) {
    //            list.add(new double[] { num, 0, 0 });
    //        } else if (type == Utils.TYPE_LIFE && list.size() < 2) {
    //            list.add(new double[] { Math.max(12, list.get(list.size() - 1)[0] + 1), 0, 0 });
    //        }

    double[] totals = new double[3];
    for (int i = 0; i < list.size(); i++) {
        double[] data = list.get(i);
        int currentType = (int) data[0];
        double ease = data[1];
        double cnt = data[2];

        totals[currentType] += cnt;
    }
    int badNew = 0;
    int badYoung = 0;
    int badMature = 0;

    mSeriesList = new double[4][list.size() + 1];

    for (int i = 0; i < list.size(); i++) {
        double[] data = list.get(i);
        int currentType = (int) data[0];
        double ease = data[1];
        double cnt = data[2];

        if (currentType == 1)
            ease += 5;
        else if (currentType == 2)
            ease += 10;

        if ((int) ease == 1) {
            badNew = i;
        }

        if ((int) ease == 6) {
            badYoung = i;
        }
        if ((int) ease == 11) {
            badMature = i;
        }
        mSeriesList[0][i] = ease;
        mSeriesList[1 + currentType][i] = cnt;
        if (cnt > mMaxCards)
            mMaxCards = (int) cnt;
    }
    mSeriesList[0][list.size()] = 15;

    mCumulative = new double[4][];
    mCumulative[0] = mSeriesList[0];
    mCumulative[1] = Utils.createCumulativeInPercent(mSeriesList[1], totals[0], badNew);
    mCumulative[2] = Utils.createCumulativeInPercent(mSeriesList[2], totals[1], badYoung);
    mCumulative[3] = Utils.createCumulativeInPercent(mSeriesList[3], totals[2], badMature);

    mMaxElements = 15; //bars are positioned from 1 to 14
    return list.size() > 0;
}

From source file:eu.thecoder4.gpl.pleftdroid.EventDetailActivity.java

/**
 * @param theurl// w w  w  .j  a va  2  s.  c o m
 */
@SuppressWarnings("static-access")
protected void initializeEventDetail(String theurl) {
    mDbAdapter = new PleftDroidDbAdapter(this);
    mDbAdapter.open();

    String json = null;
    boolean updateDesc;
    // THEURL will be null when called from Main Activity
    if (theurl == null) {
        updateDesc = false;
        // get pserver,user,vcode for this aid from DB
        Cursor adc = mDbAdapter.fetchAppointmentDetails(aid);
        while (adc.moveToNext()) {
            adesc = adc.getString(adc.getColumnIndex(PleftDroidDbAdapter.COL_DESC));
            arole = adc.getString(adc.getColumnIndex(PleftDroidDbAdapter.COL_ROLE));
            apserver = adc.getString(adc.getColumnIndex(PleftDroidDbAdapter.COL_PSERVER));
            auser = adc.getString(adc.getColumnIndex(PleftDroidDbAdapter.COL_USER));
            avcode = adc.getString(adc.getColumnIndex(PleftDroidDbAdapter.COL_VCODE));
        }
        adc.close();
        if (adesc == null || adesc.startsWith(getString(R.string.label_newappt)))
            updateDesc = true;
        if (adesc == null || adesc.startsWith("New Appointment:"))
            updateDesc = true;
        json = PleftBroker.INSTANCE.getJSONforAppointment(aid, apserver, auser, avcode);

    } else { // From Handle Links
        updateDesc = true;

        Map<String, String> arr = PleftBroker.getParamsFromURL(theurl);

        apserver = arr.get("pserver");
        if (arr.get("id") != null) {
            aid = Integer.parseInt(arr.get("id"));
        } else {
            aid = 0;
        }
        avcode = arr.get("p");
        auser = arr.get("u");
        json = PleftBroker.INSTANCE.getJSONforAppointment(aid, theurl);
        Log.i("EVDT:", "JSON=" + json);

    }
    //Toast.makeText(this, "ADesc: "+adesc+"\nupdDesc="+updateDesc, Toast.LENGTH_LONG).show();

    Gson gson = new Gson();
    EventOverview ev = null;
    try {
        ev = gson.fromJson(json, EventOverview.class);
    } catch (Exception e) {
        Log.i("EVDT:", e.toString());
        ev = null;
        initOK = false;
    }
    if (ev != null) {
        invitee = ev.getInvitee(); // The invitee param Actually indicates the Invitor!!!
        curpid = invitee;
        avails = ev.getAvailability();

        for (ADate ad : ev.getDates()) {
            adates.add(ad);
        }

        if (updateDesc) {
            adesc = ev.getMeta().getTitle();
            mDbAdapter.updateDesc(aid, adesc);
        }
        // Initialize Adapters and ListViews

        // Now we search the Invitor and we put it in the front to have it in the first Tab
        for (APerson ap : ev.getPeople()) {
            apeople.add(ap);
        }
        int i = 0;
        for (APerson ap : apeople) {
            if (ap.getId() == invitee)
                break;
            i++;
        }
        APerson a = apeople.remove(i);
        apeople.add(0, a);

        // And we initialize availabilities for people who did not yet vote
        for (APerson ap : apeople) {
            String pids = Integer.toString(ap.getId());
            for (ADate ad : adates) {
                String dids = Integer.toString(ad.getId());
                Map<String, ArrayList<String>> p = avails.get(pids);
                if (p == null) {
                    p = new HashMap<String, ArrayList<String>>();
                    avails.put(pids, p);
                }
                if (p.get(dids) == null) {
                    ArrayList<String> al = new ArrayList<String>();
                    al.add(new String("0"));
                    al.add(new String(""));
                    p.put(dids, al);

                }
            }
        }

        canproposedates = ev.getMeta().isProposeMore();
    } else {
        initOK = false;
    }
    mDbAdapter.close();

    runOnUiThread(endInit);
}

From source file:com.ichi2.anki.tests.ContentProviderTest.java

/**
 * Query .../models URI//  ww  w  . j  a  va  2s .  c o  m
 */
public void testQueryAllModels() {
    final ContentResolver cr = getContext().getContentResolver();
    // Query all available models
    final Cursor allModels = cr.query(FlashCardsContract.Model.CONTENT_URI, null, null, null, null);
    assertNotNull(allModels);
    try {
        assertTrue("Check that there is at least one result", allModels.getCount() > 0);
        while (allModels.moveToNext()) {
            long modelId = allModels.getLong(allModels.getColumnIndex(FlashCardsContract.Model._ID));
            Uri modelUri = Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI, Long.toString(modelId));
            final Cursor singleModel = cr.query(modelUri, null, null, null, null);
            assertNotNull(singleModel);
            try {
                assertEquals("Check that there is exactly one result", 1, singleModel.getCount());
                assertTrue("Move to beginning of cursor", singleModel.moveToFirst());
                String nameFromModels = allModels
                        .getString(allModels.getColumnIndex(FlashCardsContract.Model.NAME));
                String nameFromModel = singleModel
                        .getString(allModels.getColumnIndex(FlashCardsContract.Model.NAME));
                assertEquals("Check that model names are the same", nameFromModel, nameFromModels);
                String flds = allModels
                        .getString(allModels.getColumnIndex(FlashCardsContract.Model.FIELD_NAMES));
                assertTrue("Check that valid number of fields", Utils.splitFields(flds).length >= 1);
                Integer numCards = allModels
                        .getInt(allModels.getColumnIndex(FlashCardsContract.Model.NUM_CARDS));
                assertTrue("Check that valid number of cards", numCards >= 1);
            } finally {
                singleModel.close();
            }
        }
    } finally {
        allModels.close();
    }
}

From source file:com.taxicop.sync.SyncAdapter.java

public ArrayList<Complaint> query(ContentProviderClient provider, int FROM) {
    ArrayList<Complaint> reports = new ArrayList<Complaint>();
    try {//from   w ww . j ava  2 s .  c om
        Cursor c = provider.query(PlateContentProvider.URI_REPORT, null, Fields.ID_KEY + " > " + FROM + "",
                null, null);
        if (c.moveToFirst()) {
            do {
                float rank = c.getFloat(c.getColumnIndex(Fields.RANKING));
                String plate = "" + (c.getString(c.getColumnIndex(Fields.CAR_PLATE)));
                String desc = "" + (c.getString(c.getColumnIndex(Fields.DESCRIPTION)));
                String date = "" + (c.getString(c.getColumnIndex(Fields.DATE_REPORT)));
                Log.d(TAG, "plate=" + plate);
                reports.add(new Complaint(rank, plate, desc, USER, date));
            } while (c.moveToNext());
        }
        c.close();
    } catch (Exception e) {
        Log.e(TAG, "query= " + e.getMessage());
    }

    return reports;
}

From source file:com.weimed.app.sync.SyncAdapter.java

/**
 * Read JSON from an input stream, storing it into the content provider.
 *
 * <p>This is where incoming data is persisted, committing the results of a sync. In order to
 * minimize (expensive) disk operations, we compare incoming data with what's already in our
 * database, and compute a merge. Only changes (insert/update/delete) will result in a database
 * write./*  www. j a  v  a 2s .c  om*/
 *
 * <p>As an additional optimization, we use a batch operation to perform all database writes at
 * once.
 *
 * <p>Merge strategy:
 * 1. Get cursor to all items in feed<br/>
 * 2. For each item, check if it's in the incoming data.<br/>
 *    a. YES: Remove from "incoming" list. Check if data has mutated, if so, perform
 *            database UPDATE.<br/>
 *    b. NO: Schedule DELETE from database.<br/>
 * (At this point, incoming database only contains missing items.)<br/>
 * 3. For any items remaining in incoming list, ADD to database.
 */
public void updateLocalJSONData(final InputStream stream, final SyncResult syncResult)
        throws IOException, JSONException, RemoteException, OperationApplicationException, ParseException {
    final JSONParser JSONParser = new JSONParser();
    final ContentResolver contentResolver = getContext().getContentResolver();

    Log.i(TAG, "Parsing stream as JSON Array");
    final JSONObject json = JSONParser.parseJSONObject(stream);
    Log.i(TAG, "Parsing complete. Found " + json.getInt("total_rows") + " entries");

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

    // Build hash table of incoming entries
    HashMap<String, JSONObject> entryMap = new HashMap<String, JSONObject>();
    final JSONArray entries = json.getJSONArray("rows");
    for (int i = 0; i < json.getInt("total_rows"); i++) {
        JSONObject e = entries.getJSONObject(i).getJSONObject("value");
        entryMap.put(e.getString("_id"), e);
    }

    // Get list of all items
    Log.i(TAG, "Fetching local entries for merge");
    Uri uri = NewsContract.Entry.CONTENT_URI; // Get all entries
    Cursor c = contentResolver.query(uri, PROJECTION, null, null, null);
    assert c != null;
    Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution...");

    // Find stale data
    int id;
    String entryId;
    String title;
    String content;
    String publisher;
    String picurl;
    String originalurl;
    String createdat;
    String updatedat;
    String publishedat;

    while (c.moveToNext()) {
        syncResult.stats.numEntries++;
        id = c.getInt(COLUMN_ID);
        entryId = c.getString(COLUMN_ENTRY_ID);
        title = c.getString(COLUMN_TITLE);
        content = c.getString(COLUMN_CONTENT);
        publisher = c.getString(COLUMN_PUBLISHER);
        picurl = c.getString(COLUMN_PICURL);
        originalurl = c.getString(COLUMN_ORIGINALURL);
        createdat = c.getString(COLUMN_CREATEDAT);
        updatedat = c.getString(COLUMN_UPDATEDAT);
        publishedat = c.getString(COLUMN_PUBLISHEDAT);
        JSONObject match = entryMap.get(entryId);
        //            if (match != null) {
        // Entry exists. Remove from entry map to prevent insert later.
        //                entryMap.remove(entryId);
        // Check to see if the entry needs to be updated
        // How to know update local or remote? updatedAt! which is newer, update another.
        //                Uri existingUri = NewsContract.Entry.CONTENT_URI.buildUpon()
        //                                              .appendPath(Integer.toString(id)).build();
        //                if ((match.getString("title") != null && !match.getString("title").equals(title)) ||
        //                    (match.getString("content") != null && !match.getString("content").equals(content)) ||
        //                    (match.getString("publisher") != null && !match.getString("publisher").equals(publisher)) ||
        //                    (match.getString("picurl") != null && !match.getString("picurl").equals(picurl)) ||
        //                    (match.getString("originalurl") != null && !match.getString("originalurl").equals(originalurl)) ||
        //                    (match.getString("createdat") != null && !match.getString("createdat").equals(createdat)) ||
        //                    (match.getString("updatedat") != null && !match.getString("updatedat").equals(updatedat)) ||
        //                    (match.getString("publishedat") != null && !match.getString("publishedat").equals(publishedat))
        //                   ) {
        //                    // Update existing record
        //                    Log.i(TAG, "Scheduling update: " + existingUri);
        //                    batch.add(ContentProviderOperation.newUpdate(existingUri)
        //                         .withValue(NewsContract.Entry.COLUMN_TITLE, title)
        //                         .withValue(NewsContract.Entry.COLUMN_CONTENT, content)
        //                         .withValue(NewsContract.Entry.COLUMN_PUBLISHER, publisher)
        //                         .withValue(NewsContract.Entry.COLUMN_PICURL, picurl)
        //                         .withValue(NewsContract.Entry.COLUMN_ORIGINALURL, originalurl)
        //                         .withValue(NewsContract.Entry.COLUMN_CREATEDAT, createdat)
        //                         .withValue(NewsContract.Entry.COLUMN_UPDATEDAT, updatedat)
        //                         .withValue(NewsContract.Entry.COLUMN_PUBLISHEDAT, publishedat)
        //                         .build());
        //                    syncResult.stats.numUpdates++;
        //                } else {
        //                    Log.i(TAG, "No action: " + existingUri);
        //                }
        //            } else {
        // Entry doesn't exist. Remove it from the database.
        Uri deleteUri = NewsContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)).build();
        Log.i(TAG, "Scheduling delete: " + deleteUri);
        batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        syncResult.stats.numDeletes++;
        //            }
    }
    c.close();

    // Add new items
    for (JSONObject e : entryMap.values()) {
        Log.i(TAG, "Scheduling insert: entry_id=" + e.getString("_id"));
        batch.add(ContentProviderOperation.newInsert(NewsContract.Entry.CONTENT_URI)
                .withValue(NewsContract.Entry.COLUMN_ENTRY_ID, e.getString("_id"))
                .withValue(NewsContract.Entry.COLUMN_TITLE, e.getString("title"))
                .withValue(NewsContract.Entry.COLUMN_CONTENT,
                        fetchTextFileToString(NEWS_URL_BASE + '/' + e.getString("_id") + "/content.md"))
                .withValue(NewsContract.Entry.COLUMN_PUBLISHER, e.getString("publisher"))
                .withValue(NewsContract.Entry.COLUMN_PICURL, e.has("pic_link") ? e.getString("pic_link") : null)
                .withValue(NewsContract.Entry.COLUMN_ORIGINALURL, e.getString("origin_link"))
                .withValue(NewsContract.Entry.COLUMN_CREATEDAT, e.getString("created_at"))
                .withValue(NewsContract.Entry.COLUMN_UPDATEDAT, e.getString("updated_at"))
                .withValue(NewsContract.Entry.COLUMN_PUBLISHEDAT, e.getString("publish_at")).build());
        syncResult.stats.numInserts++;
    }
    Log.i(TAG, "Merge solution ready. Applying batch update");
    mContentResolver.applyBatch(NewsContract.CONTENT_AUTHORITY, batch);
    mContentResolver.notifyChange(NewsContract.Entry.CONTENT_URI, // URI where data was modified
            null, // No local observer
            false); // IMPORTANT: Do not sync to network
    // This sample doesn't support uploads, but if *your* code does, make sure you set
    // syncToNetwork=false in the line above to prevent duplicate syncs.
}

From source file:com.android.server.MaybeDatabaseHelper.java

public void listTableContents() {
    Cursor cursor = null;
    try {/*from w  ww.ja  va  2s . c  om*/
        cursor = sDatabase.query(APP_TABLE_NAME, null, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            while (true) {
                Log.v(DBTAG,
                        "Row: Package=" + cursor.getString(cursor.getColumnIndex(PACKAGE_COL)) + " | URL="
                                + cursor.getString(cursor.getColumnIndex(URL_COL)) + " | DATA="
                                + cursor.getString(cursor.getColumnIndex(DATA_COL)));
                if (cursor.isLast())
                    break;
                cursor.moveToNext();
            }
        }

    } catch (IllegalStateException e) {
        Log.e(DBTAG, "getAppDataFromDB failed", e);
    } finally {
        if (cursor != null)
            cursor.close();
    }
}

From source file:org.ohmage.sync.ResponseSyncAdapter.java

@Override
public synchronized void onPerformSync(Account account, Bundle extras, String authority,
        final ContentProviderClient provider, final SyncResult syncResult) {
    Log.d(TAG, "Start onPerformSync()");
    // Check for authtoken
    String token = null;//  w ww . j av a  2s  .c  o m
    try {
        token = am.blockingGetAuthToken(account, AuthUtil.AUTHTOKEN_TYPE, true);
    } catch (OperationCanceledException e) {
        syncResult.stats.numSkippedEntries++;
    } catch (IOException e) {
        syncResult.stats.numIoExceptions++;
    } catch (AuthenticatorException e) {
        syncResult.stats.numAuthExceptions++;
    }

    // If the token wasn't found or there was a problem, we can stop now
    if (token == null || syncResult.stats.numSkippedEntries > 0 || syncResult.stats.numIoExceptions > 0
            || syncResult.stats.numAuthExceptions > 0) {
        Log.d(TAG, "No token found or there was a problem.");
        return;
    }

    // Upload responses
    Observable<Long> toDelete = null;
    Observable<ResponseFiles> filesToDelete = null;

    Cursor cursor = null;

    try {
        cursor = provider.query(Responses.CONTENT_URI,
                new String[] { BaseColumns._ID, Responses.SURVEY_ID, Responses.SURVEY_VERSION,
                        Responses.RESPONSE_DATA, Responses.RESPONSE_METADATA, Responses.RESPONSE_EXTRAS },
                null, null, null);
        AppLogManager.getInstance().logInfo(mContext, "ResponsesSyncStarted",
                cursor.getCount() + " surveys to upload.");
        while (cursor.moveToNext()) {
            final ResponseFiles files = gson.fromJson(cursor.getString(5), ResponseFiles.class);
            try {
                // Make the call to upload responses
                Observable<Response> uploadResponse = null;

                if (Ohmage.USE_DSU_DATAPOINTS_API) {
                    uploadResponse = uploadDatapoint(cursor, files);
                } else {
                    uploadOhmagePoint(cursor, files);
                }

                // Map the data for the upload response to the local id in the db
                final long localResponseId = cursor.getLong(0);
                Observable<Long> responseId = uploadResponse.map(new Func1<Response, Long>() {
                    @Override
                    public Long call(Response response) {
                        return localResponseId;
                    }
                });

                if (toDelete == null) {
                    toDelete = responseId;
                } else {
                    toDelete = Observable.mergeDelayError(responseId, toDelete);
                }

                // Map the data for the upload response to the files in the db
                Observable<ResponseFiles> responseFiles = uploadResponse
                        .map(new Func1<Response, ResponseFiles>() {
                            @Override
                            public ResponseFiles call(Response response) {
                                return files;
                            }
                        });

                if (filesToDelete == null) {
                    filesToDelete = responseFiles;
                } else {
                    filesToDelete = Observable.mergeDelayError(responseFiles, filesToDelete);
                }
            } catch (AuthenticationException e) {
                Crashlytics.logException(e);
                Log.e(TAG, "Auth", e);
                syncResult.stats.numAuthExceptions++;
            } catch (Exception e) {
                Log.e(TAG, "Other uploading error", e);
                Crashlytics.logException(e);
            }
        }
        cursor.close();

    } catch (RemoteException e) {
        Log.e(TAG, "Remote", e);
        Crashlytics.logException(e);
        syncResult.stats.numIoExceptions++;
    } finally {
        if (cursor != null)
            cursor.close();
    }

    if (toDelete != null) {
        Log.d(TAG, "Start deleting responses.");
        toDelete.flatMap(new Func1<Long, Observable<ContentProviderOperation>>() {
            @Override
            public Observable<ContentProviderOperation> call(Long aLong) {
                return Observable.from(ContentProviderOperation.newDelete(
                        appendSyncAdapterParam(ContentUris.withAppendedId(Responses.CONTENT_URI, aLong)))
                        .build());
            }
        }).subscribe(new Subscriber<ContentProviderOperation>() {
            ArrayList<ContentProviderOperation> toDelete = new ArrayList<ContentProviderOperation>();

            @Override
            public void onCompleted() {
                try {
                    getContext().getContentResolver().applyBatch(ResponseContract.CONTENT_AUTHORITY, toDelete);
                } catch (RemoteException e) {
                    syncResult.stats.numIoExceptions++;
                } catch (OperationApplicationException e) {
                    syncResult.stats.numIoExceptions++;
                }
                unsubscribe();
            }

            @Override
            public void onError(Throwable e) {
                // Send error report
                Log.e(TAG, "Upload failed", e);
                Crashlytics.logException(e);
                onCompleted();
            }

            @Override
            public void onNext(ContentProviderOperation args) {
                toDelete.add(args);
            }
        });
    }

    if (filesToDelete != null) {
        filesToDelete.doOnNext(new Action1<ResponseFiles>() {
            @Override
            public void call(ResponseFiles responseFiles) {
                for (String s : responseFiles.getIds()) {
                    responseFiles.getFile(s).delete();
                }
            }
        }).subscribe(new Subscriber<ResponseFiles>() {
            @Override
            public void onCompleted() {
                unsubscribe();
            }

            @Override
            public void onError(Throwable e) {
                Crashlytics.logException(e);
            }

            @Override
            public void onNext(ResponseFiles responseFiles) {

            }
        });
    }
}

From source file:com.gimranov.zandy.app.task.APIRequest.java

/**
 * Produces API requests to delete queued items from the server.
 * This request always needs a key./*www .  j  ava2s  .  c o m*/
 *
 * From the API docs:
 *   DELETE /users/1/items/ABCD2345
 *   If-Match: "8e984e9b2a8fb560b0085b40f6c2c2b7"
 *
 * @param c
 * @return
 */
public static ArrayList<APIRequest> delete(Context c) {
    ArrayList<APIRequest> list = new ArrayList<APIRequest>();
    Database db = new Database(c);
    String[] args = {};
    Cursor cur = db.rawQuery("select item_key, etag from deleteditems", args);
    if (cur == null) {
        db.close();
        Log.d(TAG, "No deleted items found in database");
        return list;
    }

    do {
        APIRequest templ = new APIRequest(
                ServerCredentials.APIBASE + ServerCredentials.ITEMS + "/" + cur.getString(0), "DELETE", null);
        templ.disposition = "none";
        templ.ifMatch = cur.getString(1);
        Log.d(TAG, "Adding deleted item: " + cur.getString(0) + " : " + templ.ifMatch);
        // Save the request to the database to be dispatched later
        templ.save(db);
        list.add(templ);
    } while (cur.moveToNext() != false);
    cur.close();

    db.rawQuery("delete from deleteditems", args);
    db.close();
    return list;
}