Example usage for android.database Cursor isAfterLast

List of usage examples for android.database Cursor isAfterLast

Introduction

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

Prototype

boolean isAfterLast();

Source Link

Document

Returns whether the cursor is pointing to the position after the last row.

Usage

From source file:org.artifactly.client.service.LocalServiceImpl.java

private String getFilteredArtifacts(int filter) {

    // JSON array that holds the result
    JSONArray locations = new JSONArray();

    if (null == dbAdapter) {

        return locations.toString();
    }//from w w w  .  ja  v a2s  . c om

    // Getting all the locations
    Cursor cursor = dbAdapter.select();
    if (null == cursor) {

        return locations.toString();
    }

    // Checking if the cursor set has any items
    boolean hasItems = cursor.moveToFirst();

    if (!hasItems) {

        cursor.close();
        return locations.toString();
    }

    // Determine the table column indexes 
    int artIdColumnIndex = cursor.getColumnIndex(DbAdapter.LOC_ART_FIELDS[DbAdapter.FK_ART_ID]);
    int artNameColumnIndex = cursor.getColumnIndex(DbAdapter.ART_FIELDS[DbAdapter.ART_NAME]);
    int artDataColumnIndex = cursor.getColumnIndex(DbAdapter.ART_FIELDS[DbAdapter.ART_DATA]);
    int locIdColumnIndex = cursor.getColumnIndex(DbAdapter.LOC_ART_FIELDS[DbAdapter.FK_LOC_ID]);
    int locNameColumnIndex = cursor.getColumnIndex(DbAdapter.LOC_FIELDS[DbAdapter.LOC_NAME]);
    int longitudeColumnIndex = cursor.getColumnIndex(DbAdapter.LOC_FIELDS[DbAdapter.LOC_LONGITUDE]);
    int latitudeColumnIndex = cursor.getColumnIndex(DbAdapter.LOC_FIELDS[DbAdapter.LOC_LATITUDE]);

    String currentLocationName = null;
    JSONObject location = null;

    for (; cursor.isAfterLast() == false; cursor.moveToNext()) {

        switch (filter) {
        case CURRENT_LOCATION_ARTIFACTS_FILTER:
            // If the current location is not nearby, we don't add it
            String lat = cursor.getString(latitudeColumnIndex).trim();
            String lng = cursor.getString(longitudeColumnIndex).trim();
            if (!artifactlyService.isNearbyCurrentLocation(lat, lng)) {
                continue;
            }
            break;
        case ALL_ARTIFACTS_FILTER:
            // Don't do anything
            break;
        default:
            // Don't do anything
        }

        // Get the location
        String locationName = cursor.getString(locNameColumnIndex);

        try {

            // Check if we need to setup an new location
            if (null == currentLocationName || !currentLocationName.equals(locationName)) {

                currentLocationName = locationName;
                location = new JSONObject();
                location.put(DbAdapter.LOC_ART_FIELDS[DbAdapter.FK_LOC_ID], cursor.getInt(locIdColumnIndex));
                location.put(DbAdapter.LOC_FIELDS_AS[DbAdapter.LOC_NAME], cursor.getString(locNameColumnIndex));
                location.put(DbAdapter.LOC_FIELDS_AS[DbAdapter.LOC_LATITUDE],
                        cursor.getString(latitudeColumnIndex));
                location.put(DbAdapter.LOC_FIELDS_AS[DbAdapter.LOC_LONGITUDE],
                        cursor.getString(longitudeColumnIndex));
                location.put("artifacts", new JSONArray());
                locations.put(location);
            }

            JSONObject artifact = new JSONObject();
            artifact.put(DbAdapter.LOC_ART_FIELDS[DbAdapter.FK_ART_ID], cursor.getInt(artIdColumnIndex));
            artifact.put(DbAdapter.ART_FIELDS[DbAdapter.ART_NAME], cursor.getString(artNameColumnIndex));
            artifact.put(DbAdapter.ART_FIELDS[DbAdapter.ART_DATA], cursor.getString(artDataColumnIndex));

            location.getJSONArray("artifacts").put(artifact);

        } catch (JSONException e) {

            Log.e(PROD_LOG_TAG, "Error while populating JSONObject", e);
        }
    }

    cursor.close();

    if (locations.length() == 0) {

        return null;
    } else {

        return locations.toString();
    }
}

From source file:com.parse.OfflineStore.java

/**
 * Gets an unfetched pointer to an object in the db, based on its uuid. The object may or may not
 * be in memory, but it must be in the database. If it is already in memory, that instance will be
 * returned. Since this is only for creating pointers to objects that are referenced by other
 * objects in the data store, that's a fair assumption.
 *
 * @param uuid/*from  w  w  w. ja  v  a2  s  .  c o m*/
 *          The object to retrieve.
 * @param db
 *          The database instance to retrieve from.
 * @return The object with that UUID.
 */
private <T extends ParseObject> Task<T> getPointerAsync(final String uuid, ParseSQLiteDatabase db) {
    synchronized (lock) {
        @SuppressWarnings("unchecked")
        T existing = (T) uuidToObjectMap.get(uuid);
        if (existing != null) {
            return Task.forResult(existing);
        }
    }

    /*
     * We want to just return the pointer, but we have to look in the database to know if there's
     * something with this classname and object id already.
     */

    String[] select = { OfflineSQLiteOpenHelper.KEY_CLASS_NAME, OfflineSQLiteOpenHelper.KEY_OBJECT_ID };
    String where = OfflineSQLiteOpenHelper.KEY_UUID + " = ?";
    String[] args = { uuid };
    return db.queryAsync(OfflineSQLiteOpenHelper.TABLE_OBJECTS, select, where, args)
            .onSuccess(new Continuation<Cursor, T>() {
                @Override
                public T then(Task<Cursor> task) throws Exception {
                    Cursor cursor = task.getResult();
                    cursor.moveToFirst();
                    if (cursor.isAfterLast()) {
                        cursor.close();
                        throw new IllegalStateException("Attempted to find non-existent uuid " + uuid);
                    }

                    synchronized (lock) {
                        // We need to check again since another task might have come around and added it to
                        // the map.
                        //TODO (grantland): Maybe we should insert a Task that is resolved when the query
                        // completes like we do in getOrCreateUUIDAsync?
                        @SuppressWarnings("unchecked")
                        T existing = (T) uuidToObjectMap.get(uuid);
                        if (existing != null) {
                            return existing;
                        }

                        String className = cursor.getString(0);
                        String objectId = cursor.getString(1);
                        cursor.close();
                        @SuppressWarnings("unchecked")
                        T pointer = (T) ParseObject.createWithoutData(className, objectId);
                        /*
                         * If it doesn't have an objectId, we don't really need the UUID, and this simplifies
                         * some other logic elsewhere if we only update the map for new objects.
                         */
                        if (objectId == null) {
                            uuidToObjectMap.put(uuid, pointer);
                            objectToUuidMap.put(pointer, Task.forResult(uuid));
                        }
                        return pointer;
                    }
                }
            });
}

From source file:edu.nd.darts.cimon.MonitorReport.java

/**
 * Generate monitor report and store on SD card.
 * /*from w  w w  .j a  v  a2s.  c o m*/
 * @return true if file successfully created
 */
private boolean createFile() {

    if (DebugLog.DEBUG)
        Log.d(TAG, "MonitorReport - createFile:" + monitorId + " metric:" + metricId);
    String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        if (DebugLog.WARNING)
            Log.w(TAG, "MonitorReport.createFile - external storage not available");
        return false;
    }
    File file = new File(context.getExternalFilesDir(null), "monitor" + monitorId + ".csv");
    BufferedWriter writer;
    try {
        writer = new BufferedWriter(new FileWriter(file));

        if (metadata) {
            writer.write("sep=\t");
            writer.newLine();
            Uri metricUri = Uri.withAppendedPath(CimonContentProvider.METRICS_URI, String.valueOf(metricId));
            Cursor metricCursor = context.getContentResolver().query(metricUri, null, null, null, null);
            if (metricCursor == null) {
                if (DebugLog.WARNING)
                    Log.w(TAG, "MonitorReport.createFile - metric cursor is empty");
            } else {
                int nameCol = metricCursor.getColumnIndex(MetricsTable.COLUMN_METRIC);
                int unitsCol = metricCursor.getColumnIndex(MetricsTable.COLUMN_UNITS);
                if (metricCursor.moveToFirst()) {
                    if (nameCol < 0) {
                        if (DebugLog.WARNING)
                            Log.w(TAG, "MonitorReport.createFile - metric name column not found");
                    } else {
                        metricName = metricCursor.getString(nameCol);
                    }
                    writer.write("Metric: " + metricName);
                    writer.newLine();

                    if (unitsCol < 0) {
                        if (DebugLog.WARNING)
                            Log.w(TAG, "MonitorReport.createFile - metric name column not found");
                    } else {
                        String units = metricCursor.getString(unitsCol);
                        writer.write("Units: " + units);
                        writer.newLine();
                    }
                } else {
                    if (DebugLog.WARNING)
                        Log.w(TAG, "MonitorReport.createFile - metric cursor empty");
                }
            }
            metricCursor.close();

            Uri monitorUri = Uri.withAppendedPath(CimonContentProvider.MONITOR_URI, String.valueOf(monitorId));
            Cursor monitorCursor = context.getContentResolver().query(monitorUri, null, null, null, null);
            if (monitorCursor == null) {
                if (DebugLog.WARNING)
                    Log.w(TAG, "MonitorReport.createFile - monitor cursor is empty");
            } else {
                int offsetCol = monitorCursor.getColumnIndex(MonitorTable.COLUMN_TIME_OFFSET);
                if (monitorCursor.moveToFirst()) {
                    if (offsetCol < 0) {
                        if (DebugLog.WARNING)
                            Log.w(TAG, "MonitorReport.createFile - epoch offset column not found");
                    } else {
                        long offset = monitorCursor.getLong(offsetCol);
                        writer.write("Offset from epoch (milliseconds): " + offset);
                        writer.newLine();
                    }
                } else {
                    if (DebugLog.WARNING)
                        Log.w(TAG, "MonitorReport.createFile - monitor cursor empty");
                }
            }
            monitorCursor.close();

            writer.newLine();
        }
        writer.write("Timestamp\tValue");
        writer.newLine();

        String[] projection = { DataTable.COLUMN_TIMESTAMP, DataTable.COLUMN_VALUE };
        Uri monitorUri = Uri.withAppendedPath(CimonContentProvider.MONITOR_DATA_URI, String.valueOf(monitorId));
        Cursor mCursor = context.getContentResolver().query(monitorUri, projection, null, null, null);
        if (mCursor == null) {
            if (DebugLog.WARNING)
                Log.w(TAG, "MonitorReport.createFile - data cursor is empty");
            writer.close();
            return false;
        }
        int timestampCol = mCursor.getColumnIndex(DataTable.COLUMN_TIMESTAMP);
        if (timestampCol < 0) {
            if (DebugLog.WARNING)
                Log.w(TAG, "MonitorReport.createFile - timestamp column not found");
            mCursor.close();
            writer.close();
            return false;
        }
        int valueCol = mCursor.getColumnIndex(DataTable.COLUMN_VALUE);
        if (valueCol < 0) {
            if (DebugLog.WARNING)
                Log.w(TAG, "MonitorReport.createFile - value column not found");
            mCursor.close();
            writer.close();
            return false;
        }
        long timestamp;
        float value;
        if (mCursor.moveToFirst()) {
            while (!mCursor.isAfterLast()) {
                timestamp = mCursor.getLong(timestampCol);
                value = mCursor.getFloat(valueCol);
                writer.write(timestamp + "\t" + value);
                writer.newLine();
                mCursor.moveToNext();
            }
        }
        mCursor.close();

        writer.flush();
        writer.close();
    } catch (IOException e) {
        if (DebugLog.WARNING)
            Log.w(TAG, "MonitorReport.createFile - file writer failed");
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:babybear.akbquiz.ConfigActivity.java

/**
 * ??// w w w. j av a 2s  . c  o  m
 * 
 * @return ?
 */
private ArrayList<Music> queryMusics() {
    ArrayList<Music> musiclistResult = new ArrayList<Music>();
    ContentResolver cr = this.getContentResolver();
    Cursor musics = cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            new String[] { MediaStore.Audio.Media._ID, // int
                    MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
                    MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.DATA, // String
                    MediaStore.Audio.Media.DISPLAY_NAME, // String
                    MediaStore.Audio.Media.MIME_TYPE // String
            }, MediaStore.Audio.Media.IS_MUSIC + " = 1 AND " + MediaStore.Audio.Media.DURATION + " > 10000",
            null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
    Log.d("", "musics : " + musics.getCount());

    musics.moveToFirst();
    while (!musics.isAfterLast()) {
        Music temp = new Music();
        temp._ID = musics.getInt(musics.getColumnIndex(MediaStore.Audio.Media._ID));
        temp.ALBUM = musics.getString(musics.getColumnIndex(MediaStore.Audio.Media.ALBUM));
        temp.ARTIST = musics.getString(musics.getColumnIndex(MediaStore.Audio.Media.ARTIST));
        temp.DATA = musics.getString(musics.getColumnIndex(MediaStore.Audio.Media.DATA));
        temp.DURATION = musics.getLong(musics.getColumnIndex(MediaStore.Audio.Media.DURATION));
        temp.TITLE = musics.getString(musics.getColumnIndex(MediaStore.Audio.Media.TITLE));
        temp.isExist = true;

        musiclistResult.add(temp);
        musics.moveToNext();
    }
    musics.close();
    return musiclistResult;
}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

private void sendDisasterTweets(Long last) {
    // get disaster tweets

    Uri queryUri = Uri.parse("content://" + Tweets.TWEET_AUTHORITY + "/" + Tweets.TWEETS + "/"
            + Tweets.TWEETS_TABLE_TIMELINE + "/" + Tweets.TWEETS_SOURCE_DISASTER);

    Cursor c = getContentResolver().query(queryUri, null, null, null, null);
    Log.d(TAG, "count:" + String.valueOf(c.getCount()));
    boolean prefWebShare = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("prefWebShare",
            false);/*w  w w.  j  a  v  a2 s. c  om*/
    Log.d(TAG, "web share:" + String.valueOf(prefWebShare));
    if (c.getCount() > 0) {
        c.moveToFirst();
        while (!c.isAfterLast()) {

            try {
                if (prefWebShare) {
                    if (c.getInt(c.getColumnIndex(Tweets.COL_HTML_PAGES)) == 1) {

                        if (c.getLong(c.getColumnIndex(Tweets.COL_RECEIVED)) > (last - 10 * 60 * 1000L)) {
                            JSONObject toSend;

                            toSend = getJSON(c);
                            if (toSend != null) {
                                // if there is a photo related to this
                                // tweet, send it first!
                                if (c.getString(c.getColumnIndex(Tweets.COL_MEDIA_URIS)) != null) {
                                    sendDisasterPhoto(c);
                                }
                                Log.i(TAG, "sending tweet");
                                Log.d(TAG, toSend.toString(5));
                                bluetoothHelper.write(toSend.toString());
                            }
                            sendDisasterHtmls(c);
                        }
                    }

                } else {
                    if (c.getString(c.getColumnIndex(Tweets.COL_MEDIA_URIS)) != null) {
                        if (c.getLong(c.getColumnIndex(Tweets.COL_RECEIVED)) > (last - 5 * 60 * 1000L)) {
                            JSONObject toSend;

                            toSend = getJSON(c);
                            if (toSend != null) {
                                // if there is a photo related to this
                                // tweet, send it first!
                                if (c.getString(c.getColumnIndex(Tweets.COL_MEDIA_URIS)) != null) {
                                    sendDisasterPhoto(c);
                                }
                                Log.i(TAG, "sending tweet");
                                Log.d(TAG, toSend.toString(5));
                                bluetoothHelper.write(toSend.toString());
                            }
                        }
                    } else if (c.getLong(c.getColumnIndex(Tweets.COL_RECEIVED)) > (last - 1 * 30 * 1000L)) {
                        JSONObject toSend;

                        toSend = getJSON(c);
                        if (toSend != null) {
                            Log.i(TAG, "sending tweet");
                            Log.d(TAG, toSend.toString(5));
                            bluetoothHelper.write(toSend.toString());
                        }
                    }
                }

            } catch (JSONException e) {
                Log.e(TAG, "exception ", e);
            }

            c.moveToNext();
        }
    }
    // else
    // bluetoothHelper.write("####CLOSING_REQUEST####");
    c.close();
}

From source file:com.ziyou.selftravel.download.DownloadManager.java

/**
 * Restart the given downloads, which must have already completed
 * (successfully or not). This method will only work when called from within
 * the download manager's process.//from  w  ww  . j a v a  2s . c  om
 * 
 * @param ids the IDs of the downloads
 * @hide
 */
public void restartDownload(long... ids) {
    Cursor cursor = query(new Query().setFilterById(ids));
    try {
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS));
            if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) {
                throw new IllegalArgumentException("Cannot restart incomplete download: "
                        + cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
            }
        }
    } finally {
        cursor.close();
    }

    ContentValues values = new ContentValues();
    values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
    values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
    values.putNull(Downloads.Impl._DATA);
    values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
    values.put(Downloads.Impl.COLUMN_FAILED_CONNECTIONS, 0);
    mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
}

From source file:org.totschnig.myexpenses.fragment.CategoryList.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
    if (getActivity() == null)
        return;// w ww  . j ava2s. c om
    int id = loader.getId();
    ProtectedFragmentActivity ctx = (ProtectedFragmentActivity) getActivity();
    ActionBar actionBar = ctx.getSupportActionBar();
    switch (id) {
    case SUM_CURSOR:
        boolean[] seen = new boolean[2];
        c.moveToFirst();
        while (c.isAfterLast() == false) {
            int type = c.getInt(c.getColumnIndex(KEY_TYPE));
            updateSum(type > 0 ? "+ " : "- ", type > 0 ? incomeSumTv : expenseSumTv,
                    c.getLong(c.getColumnIndex(KEY_SUM)));
            c.moveToNext();
            seen[type] = true;
        }
        //if we have no income or expense, there is no row in the cursor
        if (!seen[1])
            updateSum("+ ", incomeSumTv, 0);
        if (!seen[0])
            updateSum("- ", expenseSumTv, 0);
        break;
    case DATEINFO_CURSOR:
        c.moveToFirst();
        actionBar.setSubtitle(mGrouping.getDisplayTitle(ctx, mGroupingYear, mGroupingSecond, c));
        thisYear = c.getInt(c.getColumnIndex(KEY_THIS_YEAR));
        thisMonth = c.getInt(c.getColumnIndex(KEY_THIS_MONTH));
        thisWeek = c.getInt(c.getColumnIndex(KEY_THIS_WEEK));
        thisDay = c.getInt(c.getColumnIndex(KEY_THIS_DAY));
        maxValue = c.getInt(c.getColumnIndex(KEY_MAX_VALUE));
        break;
    case SORTABLE_CURSOR:
        mGroupCursor = c;
        mAdapter.setGroupCursor(c);
        if (ctx.helpVariant.equals(ManageCategories.HelpVariant.distribution)) {
            if (c.getCount() > 0) {
                if (lastExpandedPosition == -1) {
                    mChart.setVisibility(showChart ? View.VISIBLE : View.GONE);
                    setData(c, mMainColors);
                    highlight(0);
                    if (showChart)
                        mListView.setItemChecked(
                                mListView.getFlatListPosition(ExpandableListView.getPackedPositionForGroup(0)),
                                true);
                }
            } else {
                mChart.setVisibility(View.GONE);
            }
        }
        if (mAccount != null) {
            actionBar.setTitle(mAccount.label);
        }
        invalidateCAB(); //only need to do this for group since children's cab does not depnd on cursor
        break;
    default:
        //check if group still exists
        if (mAdapter.getGroupId(id) != 0) {
            mAdapter.setChildrenCursor(id, c);
            if (ctx.helpVariant.equals(ManageCategories.HelpVariant.distribution)) {
                long packedPosition;
                if (c.getCount() > 0) {
                    mSubColors = getSubColors(mMainColors.get(id % mMainColors.size()));
                    setData(c, mSubColors);
                    highlight(0);
                    packedPosition = ExpandableListView.getPackedPositionForChild(id, 0);
                } else {
                    packedPosition = ExpandableListView.getPackedPositionForGroup(id);
                    if (!chartDisplaysSubs) {//check if a loader running concurrently has already switched to subs
                        highlight(id);
                    }
                }
                if (showChart && id == lastExpandedPosition) {
                    //if user has expanded a new group before loading is finished, getFlatListPosition
                    //would run in an NPE
                    mListView.setItemChecked(mListView.getFlatListPosition(packedPosition), true);
                }
            }
        }
    }
}

From source file:com.parse.OfflineStore.java

private Task<Void> deleteDataForObjectAsync(final ParseObject object, final ParseSQLiteDatabase db) {
    final Capture<String> uuid = new Capture<>();

    // Make sure the object has a UUID.
    Task<String> uuidTask;/*from w w w .  java  2 s.  c o m*/
    synchronized (lock) {
        uuidTask = objectToUuidMap.get(object);
        if (uuidTask == null) {
            // It was fetched, but it has no UUID. That must mean it isn't actually in the database.
            return Task.forResult(null);
        }
    }
    uuidTask = uuidTask.onSuccessTask(new Continuation<String, Task<String>>() {
        @Override
        public Task<String> then(Task<String> task) throws Exception {
            uuid.set(task.getResult());
            return task;
        }
    });

    // If the object was the root of a pin, unpin it.
    Task<Void> unpinTask = uuidTask.onSuccessTask(new Continuation<String, Task<Cursor>>() {
        @Override
        public Task<Cursor> then(Task<String> task) throws Exception {
            // Find all the roots for this object.
            String[] select = { OfflineSQLiteOpenHelper.KEY_KEY };
            String where = OfflineSQLiteOpenHelper.KEY_UUID + "=?";
            String[] args = { uuid.get() };
            return db.queryAsync(OfflineSQLiteOpenHelper.TABLE_DEPENDENCIES, select, where, args);
        }
    }).onSuccessTask(new Continuation<Cursor, Task<Void>>() {
        @Override
        public Task<Void> then(Task<Cursor> task) throws Exception {
            // Try to unpin this object from the pin label if it's a root of the ParsePin.
            Cursor cursor = task.getResult();
            List<String> uuids = new ArrayList<>();
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                uuids.add(cursor.getString(0));
            }
            cursor.close();

            List<Task<Void>> tasks = new ArrayList<>();
            for (final String uuid : uuids) {
                Task<Void> unpinTask = getPointerAsync(uuid, db)
                        .onSuccessTask(new Continuation<ParseObject, Task<ParsePin>>() {
                            @Override
                            public Task<ParsePin> then(Task<ParseObject> task) throws Exception {
                                ParsePin pin = (ParsePin) task.getResult();
                                return fetchLocallyAsync(pin, db);
                            }
                        }).continueWithTask(new Continuation<ParsePin, Task<Void>>() {
                            @Override
                            public Task<Void> then(Task<ParsePin> task) throws Exception {
                                ParsePin pin = task.getResult();

                                List<ParseObject> modified = pin.getObjects();
                                if (modified == null || !modified.contains(object)) {
                                    return task.makeVoid();
                                }

                                modified.remove(object);
                                if (modified.size() == 0) {
                                    return unpinAsync(uuid, db);
                                }

                                pin.setObjects(modified);
                                return saveLocallyAsync(pin, true, db);
                            }
                        });
                tasks.add(unpinTask);
            }

            return Task.whenAll(tasks);
        }
    });

    // Delete the object from the Local Datastore in case it wasn't the root of a pin.
    return unpinTask.onSuccessTask(new Continuation<Void, Task<Void>>() {
        @Override
        public Task<Void> then(Task<Void> task) throws Exception {
            String where = OfflineSQLiteOpenHelper.KEY_UUID + "=?";
            String[] args = { uuid.get() };
            return db.deleteAsync(OfflineSQLiteOpenHelper.TABLE_DEPENDENCIES, where, args);
        }
    }).onSuccessTask(new Continuation<Void, Task<Void>>() {
        @Override
        public Task<Void> then(Task<Void> task) throws Exception {
            String where = OfflineSQLiteOpenHelper.KEY_UUID + "=?";
            String[] args = { uuid.get() };
            return db.deleteAsync(OfflineSQLiteOpenHelper.TABLE_OBJECTS, where, args);
        }
    }).onSuccessTask(new Continuation<Void, Task<Void>>() {
        @Override
        public Task<Void> then(Task<Void> task) throws Exception {
            synchronized (lock) {
                // Clean up
                //TODO (grantland): we should probably clean up uuidToObjectMap and objectToUuidMap, but
                // getting the uuid requires a task and things might get a little funky...
                fetchedObjects.remove(object);
            }
            return task;
        }
    });
}

From source file:com.parse.OfflineStore.java

/**
 * Runs a ParseQuery against the store's contents. May cause any instances of T to get fetched
 * from the offline database. TODO(klimt): Should the query consider objects that are in memory,
 * but not in the offline store?//from  ww  w.  j av a 2 s. c  o  m
 *
 * @param query The query.
 * @param user The user making the query.
 * @param pin (Optional) The pin we are querying across. If null, all pins.
 * @param isCount True if we are doing a count.
 * @param db The SQLiteDatabase.
 * @param <T> Subclass of ParseObject.
 * @return The objects that match the query's constraints.
 */
private <T extends ParseObject> Task<List<T>> findAsync(final ParseQuery.State<T> query, final ParseUser user,
        final ParsePin pin, final boolean isCount, final ParseSQLiteDatabase db) {
    /*
     * This is currently unused, but is here to allow future querying across objects that are in the
     * process of being deleted eventually.
     */
    final boolean includeIsDeletingEventually = false;

    final OfflineQueryLogic queryLogic = new OfflineQueryLogic(this);

    final List<T> results = new ArrayList<>();

    Task<Cursor> queryTask;
    if (pin == null) {
        String table = OfflineSQLiteOpenHelper.TABLE_OBJECTS;
        String[] select = { OfflineSQLiteOpenHelper.KEY_UUID };
        String where = OfflineSQLiteOpenHelper.KEY_CLASS_NAME + "=?";
        if (!includeIsDeletingEventually) {
            where += " AND " + OfflineSQLiteOpenHelper.KEY_IS_DELETING_EVENTUALLY + "=0";
        }
        String[] args = { query.className() };

        queryTask = db.queryAsync(table, select, where, args);
    } else {
        Task<String> uuidTask = objectToUuidMap.get(pin);
        if (uuidTask == null) {
            // Pin was never saved locally, therefore there won't be any results.
            return Task.forResult(results);
        }

        queryTask = uuidTask.onSuccessTask(new Continuation<String, Task<Cursor>>() {
            @Override
            public Task<Cursor> then(Task<String> task) throws Exception {
                String uuid = task.getResult();

                String table = OfflineSQLiteOpenHelper.TABLE_OBJECTS + " A " + " INNER JOIN "
                        + OfflineSQLiteOpenHelper.TABLE_DEPENDENCIES + " B " + " ON A."
                        + OfflineSQLiteOpenHelper.KEY_UUID + "=B." + OfflineSQLiteOpenHelper.KEY_UUID;
                String[] select = { "A." + OfflineSQLiteOpenHelper.KEY_UUID };
                String where = OfflineSQLiteOpenHelper.KEY_CLASS_NAME + "=?" + " AND "
                        + OfflineSQLiteOpenHelper.KEY_KEY + "=?";
                if (!includeIsDeletingEventually) {
                    where += " AND " + OfflineSQLiteOpenHelper.KEY_IS_DELETING_EVENTUALLY + "=0";
                }
                String[] args = { query.className(), uuid };

                return db.queryAsync(table, select, where, args);
            }
        });
    }

    return queryTask.onSuccessTask(new Continuation<Cursor, Task<Void>>() {
        @Override
        public Task<Void> then(Task<Cursor> task) throws Exception {
            Cursor cursor = task.getResult();
            List<String> uuids = new ArrayList<>();
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                uuids.add(cursor.getString(0));
            }
            cursor.close();

            // Find objects that match the where clause.
            final ConstraintMatcher<T> matcher = queryLogic.createMatcher(query, user);

            Task<Void> checkedAllObjects = Task.forResult(null);
            for (final String uuid : uuids) {
                final Capture<T> object = new Capture<>();

                checkedAllObjects = checkedAllObjects.onSuccessTask(new Continuation<Void, Task<T>>() {
                    @Override
                    public Task<T> then(Task<Void> task) throws Exception {
                        return getPointerAsync(uuid, db);
                    }
                }).onSuccessTask(new Continuation<T, Task<T>>() {
                    @Override
                    public Task<T> then(Task<T> task) throws Exception {
                        object.set(task.getResult());
                        return fetchLocallyAsync(object.get(), db);
                    }
                }).onSuccessTask(new Continuation<T, Task<Boolean>>() {
                    @Override
                    public Task<Boolean> then(Task<T> task) throws Exception {
                        if (!object.get().isDataAvailable()) {
                            return Task.forResult(false);
                        }
                        return matcher.matchesAsync(object.get(), db);
                    }
                }).onSuccess(new Continuation<Boolean, Void>() {
                    @Override
                    public Void then(Task<Boolean> task) {
                        if (task.getResult()) {
                            results.add(object.get());
                        }
                        return null;
                    }
                });
            }

            return checkedAllObjects;
        }
    }).onSuccessTask(new Continuation<Void, Task<List<T>>>() {
        @Override
        public Task<List<T>> then(Task<Void> task) throws Exception {
            // Sort by any sort operators.
            OfflineQueryLogic.sort(results, query);

            // Apply the skip.
            List<T> trimmedResults = results;
            int skip = query.skip();
            if (!isCount && skip >= 0) {
                skip = Math.min(query.skip(), trimmedResults.size());
                trimmedResults = trimmedResults.subList(skip, trimmedResults.size());
            }

            // Trim to the limit.
            int limit = query.limit();
            if (!isCount && limit >= 0 && trimmedResults.size() > limit) {
                trimmedResults = trimmedResults.subList(0, limit);
            }

            // Fetch the includes.
            Task<Void> fetchedIncludesTask = Task.forResult(null);
            for (final T object : trimmedResults) {
                fetchedIncludesTask = fetchedIncludesTask.onSuccessTask(new Continuation<Void, Task<Void>>() {
                    @Override
                    public Task<Void> then(Task<Void> task) throws Exception {
                        return OfflineQueryLogic.fetchIncludesAsync(OfflineStore.this, object, query, db);
                    }
                });
            }

            final List<T> finalTrimmedResults = trimmedResults;
            return fetchedIncludesTask.onSuccess(new Continuation<Void, List<T>>() {
                @Override
                public List<T> then(Task<Void> task) throws Exception {
                    return finalTrimmedResults;
                }
            });
        }
    });
}

From source file:com.android.email.activity.MessageView.java

/**
 * Update the arrows based on the current position of the older/newer cursor.
 *//*from  w  ww.j  av  a  2  s.  com*/
private void updateNavigationArrows(Cursor cursor) {
    if (cursor != null) {
        boolean hasNewer, hasOlder;
        if (cursor.isAfterLast() || cursor.isBeforeFirst()) {
            // The cursor not being on a message means that the current message was not found.
            // While this should not happen, simply disable prev/next arrows in that case.
            hasNewer = hasOlder = false;
        } else {
            hasNewer = !cursor.isFirst();
            hasOlder = !cursor.isLast();
        }
        mMoveToNewer.setVisibility(hasNewer ? View.VISIBLE : View.INVISIBLE);
        mMoveToOlder.setVisibility(hasOlder ? View.VISIBLE : View.INVISIBLE);
    }
}