Example usage for android.database Cursor getLong

List of usage examples for android.database Cursor getLong

Introduction

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

Prototype

long getLong(int columnIndex);

Source Link

Document

Returns the value of the requested column as a long.

Usage

From source file:org.mythtv.service.content.v27.LiveStreamHelperV27.java

private int load(final Context context, final LocationProfile locationProfile, LiveStreamInfo[] liveStreams)
        throws RemoteException, OperationApplicationException {
    Log.d(TAG, "load : enter");

    if (null == context) {
        throw new RuntimeException("LiveStreamHelperV27 is not initialized");
    }// ww w  . j a  v a2s  .  co m

    DateTime lastModified = new DateTime(DateTimeZone.UTC);

    int processed = -1;
    int count = 0;

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

    for (LiveStreamInfo liveStream : liveStreams) {

        ContentValues values = convertLiveStreamInfoToContentValues(locationProfile, liveStream, lastModified,
                -1, null);

        String[] projection = new String[] { LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID };
        String selection = LiveStreamConstants.FIELD_ID + " = ?";
        String[] selectionArgs = new String[] { String.valueOf(liveStream.getId()) };

        selection = appendLocationHostname(context, locationProfile, selection, LiveStreamConstants.TABLE_NAME);

        Cursor cursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, projection,
                selection, selectionArgs, null);
        if (cursor.moveToFirst()) {
            Log.v(TAG, "save : updating existing liveStream info");
            long id = cursor.getLong(cursor
                    .getColumnIndexOrThrow(LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID));

            context.getContentResolver().update(ContentUris.withAppendedId(LiveStreamConstants.CONTENT_URI, id),
                    values, null, null);
        }
        cursor.close();
        count++;

        if (count > BATCH_COUNT_LIMIT) {
            Log.i(TAG, "load : applying batch for '" + count + "' transactions, processing programs");

            processBatch(context, ops, processed, count);

            count = 0;

        }

    }

    processBatch(context, ops, processed, count);

    Log.v(TAG, "load : remove deleted liveStreams");
    String deletedSelection = LiveStreamConstants.TABLE_NAME + "." + LiveStreamConstants.FIELD_LAST_MODIFIED
            + " < ?";
    String[] deletedSelectionArgs = new String[] { String.valueOf(lastModified.getMillis()) };

    deletedSelection = appendLocationHostname(context, locationProfile, deletedSelection,
            LiveStreamConstants.TABLE_NAME);

    ops.add(ContentProviderOperation.newDelete(LiveStreamConstants.CONTENT_URI)
            .withSelection(deletedSelection, deletedSelectionArgs).withYieldAllowed(true).build());

    processBatch(context, ops, processed, count);

    Intent progressIntent = new Intent(LiveStreamService.ACTION_PROGRESS);
    context.sendBroadcast(progressIntent);

    if (countLiveStreamsNotComplete(context, locationProfile) > 0) {
        Log.d(TAG, "load : further updates are required");

        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            Log.e(TAG, "load : error", e);
        }

        processed = load(context, locationProfile);
    }

    Log.d(TAG, "load : exit");
    return processed;
}

From source file:fr.free.nrw.commons.contributions.ContributionDao.java

public Contribution fromCursor(Cursor cursor) {
    // Hardcoding column positions!
    //Check that cursor has a value to avoid CursorIndexOutOfBoundsException
    if (cursor.getCount() > 0) {
        int index;
        if (cursor.getColumnIndex(Table.COLUMN_LICENSE) == -1) {
            index = 15;//from ww  w.j a va2s .  c  o  m
        } else {
            index = cursor.getColumnIndex(Table.COLUMN_LICENSE);
        }
        Contribution contribution = new Contribution(
                uriForId(cursor.getInt(cursor.getColumnIndex(Table.COLUMN_ID))),
                cursor.getString(cursor.getColumnIndex(Table.COLUMN_FILENAME)),
                parseUri(cursor.getString(cursor.getColumnIndex(Table.COLUMN_LOCAL_URI))),
                cursor.getString(cursor.getColumnIndex(Table.COLUMN_IMAGE_URL)),
                parseTimestamp(cursor.getLong(cursor.getColumnIndex(Table.COLUMN_TIMESTAMP))),
                cursor.getInt(cursor.getColumnIndex(Table.COLUMN_STATE)),
                cursor.getLong(cursor.getColumnIndex(Table.COLUMN_LENGTH)),
                parseTimestamp(cursor.getLong(cursor.getColumnIndex(Table.COLUMN_UPLOADED))),
                cursor.getLong(cursor.getColumnIndex(Table.COLUMN_TRANSFERRED)),
                cursor.getString(cursor.getColumnIndex(Table.COLUMN_SOURCE)),
                cursor.getString(cursor.getColumnIndex(Table.COLUMN_DESCRIPTION)),
                cursor.getString(cursor.getColumnIndex(Table.COLUMN_CREATOR)),
                cursor.getInt(cursor.getColumnIndex(Table.COLUMN_MULTIPLE)) == 1,
                cursor.getInt(cursor.getColumnIndex(Table.COLUMN_WIDTH)),
                cursor.getInt(cursor.getColumnIndex(Table.COLUMN_HEIGHT)), cursor.getString(index));

        String wikidataEntityId = cursor.getString(cursor.getColumnIndex(COLUMN_WIKI_DATA_ENTITY_ID));
        if (!StringUtils.isBlank(wikidataEntityId)) {
            contribution.setWikiDataEntityId(wikidataEntityId);
        }

        return contribution;
    }

    return null;
}

From source file:mx.com.adolfogarcia.popularmovies.model.view.MovieDetailViewModel.java

/**
 * Retrieves the data from the cursor passed as argument and sets it onto the
 * {@link MovieDetailViewModel}'s current {@link Movie}. The projection used
 * must be {@link MovieDetailQuery#PROJECTION}. This method
 * also notifies the data binding of the change, so the visual elements can
 * be updated./* w  w  w .  j av  a 2  s.  co m*/
 *
 * @param cursor the {@link Cursor} containing the data  to load.
 * @throws IllegalStateException if there is no {@link Movie} currently set
 *     in the {@link MovieDetailViewModel}.
 * @throws IllegalArgumentException if the data passed does not belong to
 *     the {@link Movie} currently set (i.e. does not have the same id).
 */
public void setMovieData(Cursor cursor) {
    if (mMovie == null) {
        throw new IllegalStateException("No movie currently set in MovieDetailViewModel.");
    }
    if (cursor == null) {
        return;
    }
    if (!cursor.moveToFirst()) {
        Log.w(LOG_TAG, "The cursor contains no data. Ignoring movie details.");
        return;
    }
    if (mMovie.getId() != cursor.getLong(MovieDetailQuery.COL_ID)) {
        throw new IllegalArgumentException("The data passed does not belong to the movie");
    }
    requireNonNullContext();
    requireNonNullConfiguration();
    RestfulServiceConfiguration configuration = mWeakConfiguration.get();
    Context context = mWeakContext.get();
    mMovie.setApiId(cursor.getLong(MovieDetailQuery.COL_API_ID));
    mMovie.setOriginalTitle(cursor.getString(MovieDetailQuery.COL_ORIGINAL_TITLE));
    mMovie.setReleaseDate(cursor.getLong(MovieDetailQuery.COL_RELEASE_DATE));
    mMovie.setOverview(cursor.getString(MovieDetailQuery.COL_OVERVIEW));
    int posterPixelWidth = context.getResources().getDimensionPixelSize(R.dimen.movie_poster_thumbnail_width);
    mMovie.setPosterUri(Uri.parse(configuration
            .getBestFittingPosterUrl(cursor.getString(MovieDetailQuery.COL_POSTER_PATH), posterPixelWidth)));
    int backdropPixelWidth = context.getResources().getDimensionPixelSize(R.dimen.movie_backdrop_width);
    mMovie.setBackdropUri(Uri.parse(configuration.getBestFittingPosterUrl(
            cursor.getString(MovieDetailQuery.COL_BACKDROP_PATH), backdropPixelWidth)));
    mMovie.setVoteAverage(cursor.getDouble(MovieDetailQuery.COL_VOTE_AVERAGE));
    mMovie.setUserFavorite(BooleanUtils.toBoolean(cursor.getInt(MovieDetailQuery.COL_USER_FAVORITE)));

    notifyPropertyChanged(BR._all);
}

From source file:net.kourlas.voipms_sms.Database.java

/**
 * Gets all of the messages in the database.
 *
 * @return All of the messages in the database.
 */// www.j av a 2s .c o m
public synchronized Message[] getMessages() {
    List<Message> messages = new ArrayList<>();

    Cursor cursor = database.query(TABLE_MESSAGE, columns, null, null, null, null, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Message message = new Message(cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DATABASE_ID)),
                cursor.isNull(cursor.getColumnIndexOrThrow(COLUMN_VOIP_ID)) ? null
                        : cursor.getLong(cursor.getColumnIndex(COLUMN_VOIP_ID)),
                cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DATE)),
                cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_TYPE)),
                cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_DID)),
                cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTACT)),
                cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MESSAGE)),
                cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_UNREAD)),
                cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DELETED)),
                cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DELIVERED)),
                cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DELIVERY_IN_PROGRESS)));
        messages.add(message);
        cursor.moveToNext();
    }
    cursor.close();

    Collections.sort(messages);

    Message[] messageArray = new Message[messages.size()];
    return messages.toArray(messageArray);
}

From source file:net.kourlas.voipms_sms.Database.java

/**
 * Gets the database ID for the row in the database with the specified VoIP.ms ID.
 *
 * @param voipId The VoIP.ms ID.//w  w  w  .ja v a 2s.  co  m
 * @return The database ID.
 */
private synchronized Long getDatabaseIdForVoipId(String did, long voipId) {
    Cursor cursor = database.query(TABLE_MESSAGE, columns,
            COLUMN_DID + "=" + did + " AND " + COLUMN_VOIP_ID + "=" + voipId, null, null, null, null);
    if (cursor.moveToFirst()) {
        return cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DATABASE_ID));
    }
    cursor.close();
    return null;
}

From source file:gov.nasa.arc.geocam.geocam.GeoCamService.java

public boolean uploadImage(Uri uri, int downsampleFactor) {
    final String[] projection = new String[] { MediaStore.Images.ImageColumns._ID,
            MediaStore.Images.ImageColumns.DATE_TAKEN, MediaStore.Images.ImageColumns.LATITUDE,
            MediaStore.Images.ImageColumns.LONGITUDE, MediaStore.Images.ImageColumns.DESCRIPTION,
            MediaStore.Images.ImageColumns.SIZE, };

    final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    boolean success = false;

    try {/*  w  ww. jav a2  s  .  com*/
        Cursor cur = getContentResolver().query(uri, projection, null, null, null);
        cur.moveToFirst();

        long id = cur.getLong(cur.getColumnIndex(MediaStore.Images.ImageColumns._ID));
        long dateTakenMillis = cur.getLong(cur.getColumnIndex(MediaStore.Images.ImageColumns.DATE_TAKEN));
        double latitude = cur.getDouble(cur.getColumnIndex(MediaStore.Images.ImageColumns.LATITUDE));
        double longitude = cur.getDouble(cur.getColumnIndex(MediaStore.Images.ImageColumns.LONGITUDE));
        String description = cur.getString(cur.getColumnIndex(MediaStore.Images.ImageColumns.DESCRIPTION));

        double[] angles = new double[3];
        String note;
        String tag;
        String uuid;
        String yawRef;
        try {
            JSONObject imageData = new JSONObject(description);
            angles = GeoCamMobile.rpyUnSerialize(imageData.getString("rpy"));
            note = imageData.getString("note");
            tag = imageData.getString("tag");
            uuid = imageData.getString("uuid");
            yawRef = imageData.getString("yawRef");
        } catch (JSONException e) {
            angles[0] = angles[1] = angles[2] = 0.0;
            note = "";
            tag = "";
            uuid = "";
            yawRef = GeoCamMobile.YAW_MAGNETIC;
        }

        String cameraTime = df.format(new Date(dateTakenMillis));

        Map<String, String> vars = new HashMap<String, String>();
        vars.put("cameraTime", cameraTime);
        vars.put("latitude", String.valueOf(latitude));
        vars.put("longitude", String.valueOf(longitude));
        vars.put("roll", String.valueOf(angles[0]));
        vars.put("pitch", String.valueOf(angles[1]));
        vars.put("yaw", String.valueOf(angles[2]));
        vars.put("notes", note);
        vars.put("tags", tag);
        vars.put("uuid", uuid);
        vars.put("yawRef", yawRef);

        Log.d(GeoCamMobile.DEBUG_ID, "Uploading with yawRef: " + yawRef);

        success = uploadImage(uri, id, vars, downsampleFactor);
        cur.close();
    } catch (CursorIndexOutOfBoundsException e) {
        // Bad db entry, remove from queue and report success so we can move on
        mUploadQueue.setAsUploaded(mUploadQueue.getNextFromQueue());
        Log.d(GeoCamMobile.DEBUG_ID, "Invalid entry in upload queue, removing: " + e);
        success = true;
    }
    return success;
}

From source file:gov.wa.wsdot.android.wsdot.service.MountainPassesSyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;
    long now = System.currentTimeMillis();
    boolean shouldUpdate = true;
    String responseString = "";

    /** //  ww  w  . j a va  2s  .c  om
     * Check the cache table for the last time data was downloaded. If we are within
     * the allowed time period, don't sync, otherwise get fresh data from the server.
     */
    try {
        cursor = resolver.query(Caches.CONTENT_URI, new String[] { Caches.CACHE_LAST_UPDATED },
                Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "mountain_passes" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            //long deltaMinutes = (now - lastUpdated) / DateUtils.MINUTE_IN_MILLIS;
            //Log.d(DEBUG_TAG, "Delta since last update is " + deltaMinutes + " min");
            shouldUpdate = (Math.abs(now - lastUpdated) > (15 * DateUtils.MINUTE_IN_MILLIS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Ability to force a refresh of camera data.
    boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false);

    if (shouldUpdate || forceUpdate) {
        List<Integer> starred = new ArrayList<Integer>();

        starred = getStarred();
        buildWeatherPhrases();

        try {
            URL url = new URL(MOUNTAIN_PASS_URL);
            URLConnection urlConn = url.openConnection();

            BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream());
            GZIPInputStream gzin = new GZIPInputStream(bis);
            InputStreamReader is = new InputStreamReader(gzin);
            BufferedReader in = new BufferedReader(is);

            String mDateUpdated = "";
            String jsonFile = "";
            String line;
            while ((line = in.readLine()) != null)
                jsonFile += line;
            in.close();

            JSONObject obj = new JSONObject(jsonFile);
            JSONObject result = obj.getJSONObject("GetMountainPassConditionsResult");
            JSONArray passConditions = result.getJSONArray("PassCondition");
            String weatherCondition;
            Integer weather_image;
            Integer forecast_weather_image;
            List<ContentValues> passes = new ArrayList<ContentValues>();

            int numConditions = passConditions.length();
            for (int j = 0; j < numConditions; j++) {
                JSONObject pass = passConditions.getJSONObject(j);
                ContentValues passData = new ContentValues();
                weatherCondition = pass.getString("WeatherCondition");
                weather_image = getWeatherImage(weatherPhrases, weatherCondition);

                String tempDate = pass.getString("DateUpdated");

                try {
                    tempDate = tempDate.replace("[", "");
                    tempDate = tempDate.replace("]", "");

                    String[] a = tempDate.split(",");
                    StringBuilder sb = new StringBuilder();
                    for (int m = 0; m < 5; m++) {
                        sb.append(a[m]);
                        sb.append(",");
                    }
                    tempDate = sb.toString().trim();
                    tempDate = tempDate.substring(0, tempDate.length() - 1);
                    Date date = parseDateFormat.parse(tempDate);
                    mDateUpdated = displayDateFormat.format(date);
                } catch (Exception e) {
                    Log.e(DEBUG_TAG, "Error parsing date: " + tempDate, e);
                    mDateUpdated = "N/A";
                }

                JSONArray forecasts = pass.getJSONArray("Forecast");
                JSONArray forecastItems = new JSONArray();

                int numForecasts = forecasts.length();
                for (int l = 0; l < numForecasts; l++) {
                    JSONObject forecast = forecasts.getJSONObject(l);

                    if (isNight(forecast.getString("Day"))) {
                        forecast_weather_image = getWeatherImage(weatherPhrasesNight,
                                forecast.getString("ForecastText"));
                    } else {
                        forecast_weather_image = getWeatherImage(weatherPhrases,
                                forecast.getString("ForecastText"));
                    }

                    forecast.put("weather_icon", forecast_weather_image);

                    if (l == 0) {
                        if (weatherCondition.equals("")) {
                            weatherCondition = forecast.getString("ForecastText").split("\\.")[0] + ".";
                            weather_image = forecast_weather_image;
                        }
                    }

                    forecastItems.put(forecast);
                }

                passData.put(MountainPasses.MOUNTAIN_PASS_ID, pass.getString("MountainPassId"));
                passData.put(MountainPasses.MOUNTAIN_PASS_NAME, pass.getString("MountainPassName"));
                passData.put(MountainPasses.MOUNTAIN_PASS_WEATHER_ICON, weather_image);
                passData.put(MountainPasses.MOUNTAIN_PASS_FORECAST, forecastItems.toString());
                passData.put(MountainPasses.MOUNTAIN_PASS_WEATHER_CONDITION, weatherCondition);
                passData.put(MountainPasses.MOUNTAIN_PASS_DATE_UPDATED, mDateUpdated);
                passData.put(MountainPasses.MOUNTAIN_PASS_CAMERA, pass.getString("Cameras"));
                passData.put(MountainPasses.MOUNTAIN_PASS_ELEVATION, pass.getString("ElevationInFeet"));
                passData.put(MountainPasses.MOUNTAIN_PASS_TRAVEL_ADVISORY_ACTIVE,
                        pass.getString("TravelAdvisoryActive"));
                passData.put(MountainPasses.MOUNTAIN_PASS_ROAD_CONDITION, pass.getString("RoadCondition"));
                passData.put(MountainPasses.MOUNTAIN_PASS_TEMPERATURE,
                        pass.getString("TemperatureInFahrenheit"));
                JSONObject restrictionOne = pass.getJSONObject("RestrictionOne");
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_ONE,
                        restrictionOne.getString("RestrictionText"));
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_ONE_DIRECTION,
                        restrictionOne.getString("TravelDirection"));
                JSONObject restrictionTwo = pass.getJSONObject("RestrictionTwo");
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_TWO,
                        restrictionTwo.getString("RestrictionText"));
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_TWO_DIRECTION,
                        restrictionTwo.getString("TravelDirection"));

                if (starred.contains(Integer.parseInt(pass.getString("MountainPassId")))) {
                    passData.put(MountainPasses.MOUNTAIN_PASS_IS_STARRED, 1);
                }

                passes.add(passData);

            }

            // Purge existing mountain passes covered by incoming data
            resolver.delete(MountainPasses.CONTENT_URI, null, null);
            // Bulk insert all the new mountain passes
            resolver.bulkInsert(MountainPasses.CONTENT_URI, passes.toArray(new ContentValues[passes.size()]));
            // Update the cache table with the time we did the update
            ContentValues values = new ContentValues();
            values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis());
            resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + "=?",
                    new String[] { "mountain_passes" });

            responseString = "OK";
        } catch (Exception e) {
            Log.e(DEBUG_TAG, "Error: " + e.getMessage());
            responseString = e.getMessage();
        }

    } else {
        responseString = "NOP";
    }

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.MOUNTAIN_PASSES_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);
}

From source file:com.urs.triptracks.TripUploader.java

@Override
protected Boolean doInBackground(Long... tripid) {
    // First, send the trip user asked for:
    Boolean result = uploadOneTrip(tripid[0]);

    // Then, automatically try and send previously-completed trips
    // that were not sent successfully.
    Vector<Long> unsentTrips = new Vector<Long>();

    mDb.openReadOnly();// w  w w.  j a v  a2  s . c o m
    Cursor cur = mDb.fetchUnsentTrips();
    if (cur != null && cur.getCount() > 0) {
        //pd.setMessage("Sent. You have previously unsent trips; submitting those now.");
        while (!cur.isAfterLast()) {
            //HS-unsentTrips.add(new Long(cur.getLong(0)));Use Long.valueOf(cur.getLong(0)) instead
            unsentTrips.add(Long.valueOf(cur.getLong(0)));
            cur.moveToNext();
        }
        cur.close();
    }
    mDb.close();

    for (Long trip : unsentTrips) {
        result &= uploadOneTrip(trip);
    }
    return result;
}

From source file:net.potterpcs.recipebook.RecipeData.java

public long getLastInsertRecipeId() {
    synchronized (DB_LOCK) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = db.rawQuery("select max(_id) from " + RECIPES_TABLE, null);
        c.moveToFirst();/*from w  w w  . jav  a 2s. c o  m*/
        long id = c.getLong(0);
        c.close();
        return id;
    }
}

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

/**
 * Queries the transfer record specified by main upload id.
 *
 * @param mainUploadId The mainUploadId of a multipart upload task
 * @return The bytes already uploaded for this multipart upload task
 */// w w  w.  j  a  v a  2  s .com
public long queryBytesTransferredByMainUploadId(int mainUploadId) {
    Cursor c = null;
    long bytesTotal = 0;
    try {
        c = transferDBBase.query(getPartUri(mainUploadId), null, null, null, null);
        while (c.moveToNext()) {
            final String state = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_STATE));
            if (TransferState.PART_COMPLETED.equals(TransferState.getState(state))) {
                bytesTotal += c.getLong(c.getColumnIndexOrThrow(TransferTable.COLUMN_BYTES_TOTAL));
            }
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return bytesTotal;
}