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.opensmc.mytracks.cyclesmc.TripUploader.java

private JSONObject getCoordsJSON(long tripId) throws JSONException {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

    mDb.openReadOnly();/*from w ww.j a  v a 2 s .  c  om*/
    Cursor tripCoordsCursor = mDb.fetchAllCoordsForTrip(tripId);

    // Build the map between JSON fieldname and phone db fieldname:
    Map<String, Integer> fieldMap = new HashMap<String, Integer>();
    fieldMap.put(TRIP_COORDS_TIME, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_TIME));
    fieldMap.put(TRIP_COORDS_LAT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LAT));
    fieldMap.put(TRIP_COORDS_LON, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LGT));
    fieldMap.put(TRIP_COORDS_ALT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ALT));
    fieldMap.put(TRIP_COORDS_SPEED, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_SPEED));
    fieldMap.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC));
    fieldMap.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC));

    // Build JSON objects for each coordinate:
    JSONObject tripCoords = new JSONObject();
    while (!tripCoordsCursor.isAfterLast()) {
        JSONObject coord = new JSONObject();

        coord.put(TRIP_COORDS_TIME, df.format(tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_TIME))));
        coord.put(TRIP_COORDS_LAT, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LAT)));
        coord.put(TRIP_COORDS_LON, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LON)));
        coord.put(TRIP_COORDS_ALT, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_ALT)));
        coord.put(TRIP_COORDS_SPEED, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_SPEED)));
        coord.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_HACCURACY)));
        coord.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_VACCURACY)));

        tripCoords.put(coord.getString("rec"), coord);
        tripCoordsCursor.moveToNext();
    }
    tripCoordsCursor.close();
    mDb.close();
    return tripCoords;
}

From source file:com.aengbee.android.leanback.ui.PlaybackOverlayCustomFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    if (cursor != null && cursor.moveToFirst()) {
        switch (loader.getId()) {
        case QUEUE_VIDEOS_LOADER: {
            mQueue.clear();/*from w  w  w  .  java2  s .  com*/
            while (!cursor.isAfterLast()) {
                Video v = (Video) mVideoCursorMapper.convert(cursor);

                // Set the queue index to the selected video.
                if (v.id == mSelectedVideo.id) {
                    mQueueIndex = mQueue.size();
                }

                // Add the video to the queue.
                MediaSessionCompat.QueueItem item = getQueueItem(v);
                mQueue.add(item);

                cursor.moveToNext();
            }

            mSession.setQueue(mQueue);
            mSession.setQueueTitle(getString(R.string.queue_name));
            break;
        }
        case RECOMMENDED_VIDEOS_LOADER: {
            mVideoCursorAdapter.changeCursor(cursor);
            break;
        }
        case 0: {
            /*
            int titleRes;
            if (cursor != null && cursor.moveToFirst()) {
                mResultsFound = true;
                titleRes = R.string.search_results;
            } else {
                mResultsFound = false;
                titleRes = R.string.no_search_results;
            }
            mVideoCursorAdapter.changeCursor(cursor);
            HeaderItem header = new HeaderItem(getString(titleRes, mQuery));
            mRowsAdapter.clear();
            ListRow row = new ListRow(header, mVideoCursorAdapter);
            mRowsAdapter.add(row);
            setAdapter(mRowsAdapter);
            break;
            */

            // Playing a specific video.
            Video video = (Video) mVideoCursorMapper.convert(cursor);
            playVideo(video, mAutoPlayExtras);
            break;
        }
        default: {

            mVideoCursorAdapter.changeCursor(cursor);

            break;
        }
        }
    }
}

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

public String getLocations() {

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

    if (null == dbAdapter) {

        return items.toString();
    }//from ww w .ja v a  2s.  co m

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

        return items.toString();
    }

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

    if (!hasItems) {

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

    // Determine the table column indexes
    int locIdColumnIndex = cursor.getColumnIndex(DbAdapter.LOC_FIELDS[DbAdapter.LOC_ID]);
    int locNameColumnIndex = cursor.getColumnIndex(DbAdapter.LOC_FIELDS[DbAdapter.LOC_NAME]);
    int locLatColumnIndex = cursor.getColumnIndex(DbAdapter.LOC_FIELDS[DbAdapter.LOC_LATITUDE]);
    int locLngColumnIndex = cursor.getColumnIndex(DbAdapter.LOC_FIELDS[DbAdapter.LOC_LONGITUDE]);

    /*
     *  Iterating over all result and calculate the distance between
     *  radius, we notify the user that there is an artifact.
     */
    for (; cursor.isAfterLast() == false; cursor.moveToNext()) {

        JSONObject item = new JSONObject();

        try {

            item.put(DbAdapter.LOC_FIELDS_AS[DbAdapter.LOC_ID], cursor.getInt(locIdColumnIndex));
            item.put(DbAdapter.LOC_FIELDS_AS[DbAdapter.LOC_NAME], cursor.getString(locNameColumnIndex));
            item.put(DbAdapter.LOC_FIELDS_AS[DbAdapter.LOC_LATITUDE], cursor.getString(locLatColumnIndex));
            item.put(DbAdapter.LOC_FIELDS_AS[DbAdapter.LOC_LONGITUDE], cursor.getString(locLngColumnIndex));
        } catch (JSONException e) {

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

        items.put(item);
    }

    cursor.close();

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

        return null;
    } else {

        return items.toString();
    }
}

From source file:edu.mit.mobile.android.locast.sync.SyncEngine.java

/**
 * Uploads any unpublished casts./*from   w w w . j  a v  a2s .  c  om*/
 *
 * This is the method that does all the hard work.
 *
 * @param toSync
 * @param provider
 * @param syncMap
 * @param syncResult
 * @return the number of casts uploaded.
 * @throws JSONException
 * @throws NetworkProtocolException
 * @throws IOException
 * @throws NoPublicPath
 * @throws RemoteException
 * @throws OperationApplicationException
 * @throws SyncException
 * @throws InterruptedException
 */
private int uploadUnpublished(Uri toSync, Account account, ContentProviderClient provider, SyncMap syncMap,
        HashMap<String, SyncEngine.SyncStatus> syncStatuses, SyncResult syncResult)
        throws JSONException, NetworkProtocolException, IOException, NoPublicPath, RemoteException,
        OperationApplicationException, SyncException, InterruptedException {
    int count = 0;

    final String type = provider.getType(toSync);
    final boolean isDir = type.startsWith(CONTENT_TYPE_PREFIX_DIR);

    final Cursor uploadMe = provider.query(toSync, null, SELECTION_UNPUBLISHED, null, null);

    if (uploadMe == null) {
        throw new SyncException("could not query " + toSync);
    }

    final int idCol = uploadMe.getColumnIndex(JsonSyncableItem._ID);

    try {
        for (uploadMe.moveToFirst(); !uploadMe.isAfterLast(); uploadMe.moveToNext()) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final long id = uploadMe.getLong(idCol);

            final Uri localUri = isDir ? ContentUris.withAppendedId(toSync, id) : toSync;
            final String postUri = MediaProvider.getPostPath(mContext, localUri);

            Intent intent = new Intent(SYNC_STATUS_CHANGED);
            intent.putExtra(EXTRA_SYNC_STATUS, "castBegin");
            intent.putExtra(EXTRA_SYNC_ID, id);
            mContext.sendStickyBroadcast(intent);

            try {
                final JSONObject jo = JsonSyncableItem.toJSON(mContext, localUri, uploadMe, syncMap);

                if (DEBUG) {
                    Log.d(TAG, "uploading " + localUri + " to " + postUri);
                }

                // Upload! Any non-successful responses are handled by
                // exceptions.
                final HttpResponse res = mNetworkClient.post(postUri, jo.toString());

                long serverTime;
                try {
                    serverTime = getServerTime(res);
                    // We should never get a corrupted date from the server,
                    // but if it does happen,
                    // using the local time is a sane fallback.
                } catch (final DateParseException e) {
                    serverTime = System.currentTimeMillis();
                }

                // newly-created items return the JSON serialization of the
                // object as the server
                // knows it, so the local database needs to be updated to
                // reflect that.
                final JSONObject newJo = NetworkClient.toJsonObject(res);
                try {
                    final SyncStatus ss = loadItemFromJsonObject(newJo, syncMap, serverTime);

                    // update immediately, so that any cancellation or
                    // interruption of the sync
                    // keeps the local state in sync with what's on the
                    // server
                    final int updates = provider.update(localUri, ss.remoteCVs, null, null);

                    final String locUriString = localUri.toString();

                    if (updates == 1) {
                        ss.state = SyncState.NOW_UP_TO_DATE;
                        ss.local = localUri;

                        // ensure that it's findable by local URI too
                        syncStatuses.put(locUriString, ss);

                        syncMap.onPostSyncItem(mContext, account, ss.local, ss.remoteJson, true);

                        count++;
                        syncResult.stats.numUpdates++;

                    } else {
                        Log.e(TAG, "error updating " + locUriString);

                        syncResult.stats.numSkippedEntries++;
                    }

                    syncResult.stats.numEntries++;

                } catch (final JSONException e) {
                    if (DEBUG) {
                        Log.e(TAG, "result was " + newJo.toString());
                    }
                    throw e;
                }
            } finally {
                intent = new Intent(SYNC_STATUS_CHANGED);
                intent.putExtra(EXTRA_SYNC_STATUS, "castEnd");
                intent.putExtra(EXTRA_SYNC_ID, id);
                mContext.sendStickyBroadcast(intent);
            }
        }
    } finally {
        uploadMe.close();
    }

    return count;
}

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

private void sendDisasterDM(Long last) {

    Uri uriQuery = Uri.parse("content://" + DirectMessages.DM_AUTHORITY + "/" + DirectMessages.DMS + "/"
            + DirectMessages.DMS_LIST + "/" + DirectMessages.DMS_SOURCE_DISASTER);
    Cursor c = getContentResolver().query(uriQuery, null, null, null, null);
    Log.i(TAG, "c.getCount: " + c.getCount());
    if (c.getCount() > 0) {
        c.moveToFirst();//from  w  ww  . j a  va 2s .c om

        while (!c.isAfterLast()) {
            if (c.getLong(c.getColumnIndex(DirectMessages.COL_RECEIVED)) > (last - 1 * 30 * 1000L)) {
                JSONObject dmToSend;

                try {
                    dmToSend = getDmJSON(c);
                    if (dmToSend != null) {
                        Log.i(TAG, "sending dm");

                        bluetoothHelper.write(dmToSend.toString());
                    }

                } catch (JSONException ex) {
                }
            }
            c.moveToNext();
        }
    }
    c.close();

}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.messagehandler.MessageHandler.java

/**
 * Starts to restore the subscriberHashMap from a database
 *//*from w w w  .j av  a2  s.c o m*/
private void restoreSubscriptionsFromDB() {
    Log.i(TAG, "Restore Subscriptions From DB");

    db.openReadableDB();
    Cursor c = db.getAllRecords();
    if (c.moveToFirst()) {
        while (!c.isAfterLast()) {
            sendSubscription(c);
            c.moveToNext();
        }
    }
    db.close();
    printAdvertisementsAndSubscriptions();
}

From source file:com.silentcircle.contacts.list.PhoneNumberListAdapter.java

@Override
protected void bindView(View itemView, int partition, Cursor cursor, int position) {
    ContactListItemView view = (ContactListItemView) itemView;

    view.setHighlightedPrefix(isSearchMode() ? getUpperCaseQueryString() : null);

    // Look at elements before and after this position, checking if contact IDs are same.
    // If they have one same contact ID, it means they can be grouped.
    ///*from www. jav  a  2 s .  c om*/
    // In one group, only the first entry will show its photo and its name, and the other
    // entries in the group show just their data (e.g. phone number, email address).
    cursor.moveToPosition(position);
    boolean isFirstEntry = true;
    boolean showBottomDivider = true;
    final long currentContactId = cursor.getLong(PhoneQuery.PHONE_CONTACT_ID);
    if (cursor.moveToPrevious() && !cursor.isBeforeFirst()) {
        final long previousContactId = cursor.getLong(PhoneQuery.PHONE_CONTACT_ID);
        if (currentContactId == previousContactId) {
            isFirstEntry = false;
        }
    }
    cursor.moveToPosition(position);
    if (cursor.moveToNext() && !cursor.isAfterLast()) {
        final long nextContactId = cursor.getLong(PhoneQuery.PHONE_CONTACT_ID);
        if (currentContactId == nextContactId) {
            // The following entry should be in the same group, which means we don't want a
            // divider between them.
            // TODO: we want a different divider than the divider between groups. Just hiding
            // this divider won't be enough.
            showBottomDivider = false;
        }
    }
    cursor.moveToPosition(position);

    bindSectionHeaderAndDivider(view, position);
    if (isFirstEntry) {
        bindName(view, cursor);
        if (isQuickContactEnabled()) {
            // No need for photo uri here, because we can not have directory results. If we
            // ever do, we need to add photo uri to the query
            bindQuickContact(view, partition, cursor, PhoneQuery.PHONE_PHOTO_ID, -1,
                    PhoneQuery.PHONE_CONTACT_ID);
        } else {
            bindPhoto(view, cursor);
        }
    } else {
        unbindName(view);

        view.removePhotoView(true, false);
    }
    bindPhoneNumber(view, cursor);
    view.setDividerVisible(showBottomDivider);
}

From source file:io.github.mkjung.ivi.media.MediaDatabase.java

/**
 *
 * @return//  w ww  .  j ava 2s . co m
 */
public synchronized List<File> getMediaDirs() {

    List<File> paths = new ArrayList<File>();
    Cursor cursor;

    cursor = mDb.query(DIR_TABLE_NAME, new String[] { DIR_ROW_PATH }, null, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        if (!cursor.isAfterLast()) {
            do {
                File dir = new File(cursor.getString(0));
                paths.add(dir);
            } while (cursor.moveToNext());
        }
        cursor.close();
    }

    return paths;
}

From source file:edu.gatech.ppl.cycleatlanta.TripUploader.java

private JSONObject getCoordsJSON(long tripId) throws JSONException {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    mDb.openReadOnly();/*ww w  . j a v a 2s .  c om*/
    Cursor tripCoordsCursor = mDb.fetchAllCoordsForTrip(tripId);

    // Build the map between JSON fieldname and phone db fieldname:
    Map<String, Integer> fieldMap = new HashMap<String, Integer>();
    fieldMap.put(TRIP_COORDS_TIME, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_TIME));
    fieldMap.put(TRIP_COORDS_LAT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LAT));
    fieldMap.put(TRIP_COORDS_LON, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LGT));
    fieldMap.put(TRIP_COORDS_ALT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ALT));
    fieldMap.put(TRIP_COORDS_SPEED, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_SPEED));
    fieldMap.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC));
    fieldMap.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC));

    // Build JSON objects for each coordinate:
    JSONObject tripCoords = new JSONObject();
    while (!tripCoordsCursor.isAfterLast()) {
        JSONObject coord = new JSONObject();

        coord.put(TRIP_COORDS_TIME, df.format(tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_TIME))));
        coord.put(TRIP_COORDS_LAT, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LAT)) / 1E6);
        coord.put(TRIP_COORDS_LON, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LON)) / 1E6);
        coord.put(TRIP_COORDS_ALT, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_ALT)));
        coord.put(TRIP_COORDS_SPEED, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_SPEED)));
        coord.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_HACCURACY)));
        coord.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_VACCURACY)));

        tripCoords.put(coord.getString("r"), coord);
        tripCoordsCursor.moveToNext();
    }
    tripCoordsCursor.close();
    mDb.close();
    return tripCoords;
}

From source file:io.github.mkjung.ivi.media.MediaDatabase.java

/**
 * Get all paths from the items in the database
 * @return list of File// w w  w  . jav a2  s.com
 */
@SuppressWarnings("unused")
private synchronized HashSet<File> getMediaFiles() {

    HashSet<File> files = new HashSet<File>();
    Cursor cursor;

    cursor = mDb.query(MEDIA_TABLE_NAME, new String[] { MEDIA_LOCATION }, null, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        if (!cursor.isAfterLast()) {
            do {
                File file = new File(cursor.getString(0));
                files.add(file);
            } while (cursor.moveToNext());
        }
        cursor.close();
    }

    return files;
}