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:com.xorcode.andtweet.FriendTimeline.java

/**
 * Remove old records to ensure that the database does not grow too large.
 * Maximum number of records is configured in "history_size" preference
 * /*from  w w w. j a  v  a 2s .co  m*/
 * @return Number of deleted records
 */
public int pruneOldRecords() {
    int nDeleted = 0;
    int nDeletedTime = 0;
    // We're using global preferences here
    SharedPreferences sp = MyPreferences.getDefaultSharedPreferences();
    int maxDays = Integer.parseInt(sp.getString(MyPreferences.KEY_HISTORY_TIME, "3"));
    long sinceTimestamp = 0;
    if (maxDays > 0) {
        sinceTimestamp = System.currentTimeMillis() - maxDays * (1000L * 60 * 60 * 24);

        SelectionAndArgs sa = new SelectionAndArgs();
        sa.addSelection(AndTweetDatabase.Tweets.SENT_DATE + " <  ?",
                new String[] { String.valueOf(sinceTimestamp) });

        if (mTimelineType != AndTweetDatabase.Tweets.TIMELINE_TYPE_MESSAGES) {
            // Don't delete Favorites!
            sa.addSelection(AndTweetDatabase.Tweets.FAVORITED + " = ?", new String[] { "0" });
        }
        nDeletedTime = mContentResolver.delete(mContentUri, sa.selection, sa.selectionArgs);
    }

    int nTweets = 0;
    int nToDeleteSize = 0;
    int nDeletedSize = 0;
    int maxSize = Integer.parseInt(sp.getString(MyPreferences.KEY_HISTORY_SIZE, "2000"));
    long sinceTimestampSize = 0;
    if (maxSize > 0) {
        try {

            nDeletedSize = 0;
            Cursor cursor = mContentResolver.query(mContentCountUri, null, null, null, null);
            if (cursor.moveToFirst()) {
                // Count is in the first column
                nTweets = cursor.getInt(0);
                nToDeleteSize = nTweets - maxSize;
            }
            cursor.close();
            if (nToDeleteSize > 0) {
                // Find SENT_DATE of the most recent tweet to delete
                cursor = mContentResolver.query(mContentUri, new String[] { AndTweetDatabase.Tweets.SENT_DATE },
                        null, null, "sent ASC LIMIT 0," + nToDeleteSize);
                if (cursor.moveToLast()) {
                    sinceTimestampSize = cursor.getLong(0);
                }
                cursor.close();
                if (sinceTimestampSize > 0) {
                    SelectionAndArgs sa = new SelectionAndArgs();
                    sa.addSelection(AndTweetDatabase.Tweets.SENT_DATE + " <=  ?",
                            new String[] { String.valueOf(sinceTimestampSize) });
                    if (mTimelineType != AndTweetDatabase.Tweets.TIMELINE_TYPE_MESSAGES) {
                        sa.addSelection(AndTweetDatabase.Tweets.FAVORITED + " = ?", new String[] { "0" });
                    }
                    nDeletedSize = mContentResolver.delete(mContentUri, sa.selection, sa.selectionArgs);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "pruneOldRecords failed");
            e.printStackTrace();
        }
    }
    nDeleted = nDeletedTime + nDeletedSize;
    if (MyLog.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "pruneOldRecords; History time=" + maxDays + " days; deleted " + nDeletedTime + " , since "
                + sinceTimestamp + ", now=" + System.currentTimeMillis());
        Log.v(TAG, "pruneOldRecords; History size=" + maxSize + " tweets; deleted " + nDeletedSize + " of "
                + nTweets + " tweets, since " + sinceTimestampSize);
    }

    return nDeleted;
}

From source file:com.mio.jrdv.sunshine.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city/*from   w w w .  jav  a  2 s. c  o  m*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */

//este metodo lo he tenido que hace public para poder accederlo desde el TEstFetchWeatherTask!!

public long addLocation(String locationSetting, String cityName, double lat, double lon) {
    // Students: First, check if the location with this city name exists in the db
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI
    // return 0;
    long locationId;

    // First, check if the location with this city name exists in the db
    Cursor locationCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting },
            null);
    // WeatherContract.LocationEntry.CONTENT_URI:
    //  ES content://com.mio.jrdv.sunshine.app/location

    if (locationCursor.moveToFirst()) {
        int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = locationCursor.getLong(locationIdIndex);
    } else {
        // Now that the content provider is set up, inserting rows of data is pretty simple.
        // First create a ContentValues object to hold the data you want to insert.
        ContentValues locationValues = new ContentValues();

        // Then add the data, along with the corresponding name of the data type,
        // so the content provider knows what kind of value is being inserted.
        locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        // Finally, insert location data into the database.
        Uri insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);

        // The resulting URI contains the ID for the row.  Extract the locationId from the Uri.
        locationId = ContentUris.parseId(insertedUri);
    }

    locationCursor.close();
    // Wait, that worked?  Yes!
    return locationId;
}

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

public Recipe getSingleRecipeObject(long rid) {
    Recipe r = new Recipe();
    Cursor c = getSingleRecipe(rid);
    c.moveToFirst();/*from w  w w . jav  a  2s  . co m*/
    r.id = c.getLong(c.getColumnIndex(RT_ID));
    r.name = c.getString(c.getColumnIndex(RT_NAME));
    r.description = c.getString(c.getColumnIndex(RT_DESCRIPTION));
    r.rating = c.getFloat(c.getColumnIndex(RT_RATING));
    r.creator = c.getString(c.getColumnIndex(RT_CREATOR));
    r.date = c.getString(c.getColumnIndex(RT_DATE));
    r.serving = c.getInt(c.getColumnIndex(RT_SERVING));
    r.time = c.getInt(c.getColumnIndex(RT_TIME));
    r.photo = c.getString(c.getColumnIndex(RT_PHOTO));

    r.ingredients = getRecipeIngredientStrings(rid);
    r.directions = getRecipeDirectionStrings(rid);
    r.directions_photos = getRecipeDirectionPhotoStrings(rid);
    r.tags = getRecipeTagStrings(rid);

    c.close();
    return r;
}

From source file:ru.gkpromtech.exhibition.db.Table.java

private void fillFieldValue(int type, Field field, Object entity, Cursor cursor, int i)
        throws IllegalAccessException {
    if (cursor.isNull(i)) {
        field.set(entity, null);/*from  w w  w .  j a va 2s  . c om*/
        return;
    }
    switch (type) {
    case INTEGER:
        field.set(entity, cursor.getInt(i));
        break;
    case SHORT:
        field.set(entity, cursor.getShort(i));
        break;
    case LONG:
        field.set(entity, cursor.getLong(i));
        break;
    case FLOAT:
        field.set(entity, cursor.getFloat(i));
        break;
    case DOUBLE:
        field.set(entity, cursor.getDouble(i));
        break;
    case STRING:
        field.set(entity, cursor.getString(i));
        break;
    case BYTE_ARRAY:
        field.set(entity, cursor.getBlob(i));
        break;
    case DATE:
        field.set(entity, new Date(cursor.getLong(i)));
        break;
    case BOOLEAN:
        field.set(entity, cursor.getInt(i) != 0);
        break;
    }
}

From source file:org.mythtv.service.dvr.v26.ProgramHelperV26.java

public void processProgram(final Context context, final LocationProfile locationProfile, Uri uri, String table,
        ArrayList<ContentProviderOperation> ops, Program program, String tag) {
    //      Log.d( TAG, "processProgram : enter" );

    ContentValues programValues = convertProgramToContentValues(locationProfile, program, tag);

    if (table.equals(ProgramConstants.TABLE_NAME_RECORDED) || table.equals(ProgramConstants.TABLE_NAME_UPCOMING)
            || table.equals(ProgramConstants.TABLE_NAME_GUIDE)) {

        //Log.v( TAG, "processProgram : INSERT PROGRAM : " + program.getTitle() + ":" + program.getSubTitle() + ":" + program.getChannelInfo().getChannelId() + ":" + program.getStartTime() + ":" + program.getEndTime() + ":" + program.getHostname() + ":" + table );
        ops.add(ContentProviderOperation.newInsert(uri).withValues(programValues).withYieldAllowed(true)
                .build());/*www.ja  v a2 s  . c o m*/

    } else {

        String programSelection = table + "." + ProgramConstants.FIELD_CHANNEL_ID + " = ? AND " + table + "."
                + ProgramConstants.FIELD_START_TIME + " = ?";
        String[] programSelectionArgs = new String[] { String.valueOf(program.getChannel().getChanId()),
                String.valueOf(program.getStartTime().getMillis()) };

        programSelection = appendLocationHostname(context, locationProfile, programSelection, table);

        Cursor programCursor = context.getContentResolver().query(uri, programProjection, programSelection,
                programSelectionArgs, null);
        if (programCursor.moveToFirst()) {
            Log.v(TAG,
                    "processProgram : UPDATE PROGRAM : " + program.getTitle() + ":" + program.getSubTitle()
                            + ":" + program.getChannel().getChanId() + ":" + program.getStartTime() + ":"
                            + program.getEndTime() + ":" + program.getHostName() + ":" + table);

            Long id = programCursor.getLong(programCursor.getColumnIndexOrThrow(ProgramConstants._ID));
            ops.add(ContentProviderOperation.newUpdate(ContentUris.withAppendedId(uri, id))
                    .withValues(programValues).withYieldAllowed(true).build());

        } else {
            //Log.v( TAG, "processProgram : INSERT PROGRAM : " + program.getTitle() + ":" + program.getSubTitle() + ":" + program.getChannel().getChanId() + ":" + program.getStartTime() + ":" + program.getEndTime() + ":" + program.getHostName() + ":" + table );

            ops.add(ContentProviderOperation.newInsert(uri).withValues(programValues).withYieldAllowed(true)
                    .build());

        }
        programCursor.close();

    }

    //      Log.d( TAG, "processProgram : exit" );
}

From source file:at.bitfire.davdroid.resource.LocalCalendar.java

void populateExceptions(Event e) throws RemoteException {
    @Cleanup
    Cursor c = providerClient.query(syncAdapterURI(Events.CONTENT_URI),
            new String[] { Events._ID, entryColumnRemoteName() }, Events.ORIGINAL_ID + "=?",
            new String[] { String.valueOf(e.getLocalID()) }, null);
    while (c != null && c.moveToNext()) {
        long exceptionId = c.getLong(0);
        String exceptionRemoteName = c.getString(1);
        try {//from  w  ww  . ja v a  2 s .  c om
            Event exception = new Event(exceptionId, exceptionRemoteName, null);
            populate(exception);
            e.getExceptions().add(exception);
        } catch (LocalStorageException ex) {
            Log.e(TAG, "Couldn't find exception details, ignoring");
        }
    }
}

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

@SuppressLint("UseValueOf")
private Object getModelValueFor(Cursor query, String fieldName, FieldType fieldType) throws JSONException {

    int columnIndex = query.getColumnIndex(fieldName);
    if (query.isNull(columnIndex)) {
        return null;
    }/*from  w w w .j  a  v  a 2s.  c  o m*/
    switch (fieldType) {
    case Boolean:
        return new Boolean(query.getInt(columnIndex) != 0);
    case Date:
        return format.format(new Date(query.getLong(columnIndex)));
    case Numeric:
        return new Long(query.getLong(columnIndex));
    case Text:
        return query.getString(columnIndex);
    case JsonObject:
        String json = query.getString(columnIndex);
        return new JSONObject(json);
    case JsonArray:
        json = query.getString(columnIndex);
        return new JSONArray(json);
    default:
        return null;
    }
}

From source file:com.flowzr.budget.holo.export.flowzr.FlowzrSyncEngine.java

public static Object pushDelete() throws Exception {
    String sql = "select count(*) from " + DatabaseHelper.DELETE_LOG_TABLE;
    Cursor cursorCursor = db.rawQuery(sql, null);
    cursorCursor.moveToFirst();//from  ww  w . ja  v  a2  s  .c  o m
    long total = cursorCursor.getLong(0);
    cursorCursor.close();
    Cursor cursor = db.rawQuery("select table_name,remote_key from delete_log", null);
    int i = 0;
    String del_list = "";
    if (cursor.moveToFirst()) {
        do {
            //notifyUser("push delete",(int)(Math.round(i*100/total)));
            del_list += cursor.getString(1) + ";";
            i++;
        } while (cursor.moveToNext());
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("action", "pushDelete"));
        nameValuePairs.add(new BasicNameValuePair("remoteKey", del_list));
        httpPush(nameValuePairs, "delete");
    }
    cursor.close();
    return null;
}

From source file:org.mythtv.service.content.v25.LiveStreamHelperV25.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("LiveStreamHelperV25 is not initialized");
    }/*from   ww w  .  ja va2 s  .  com*/

    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, "load : 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:org.mythtv.service.content.v26.LiveStreamHelperV26.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("LiveStreamHelperV26 is not initialized");
    }/*  w  w w  .ja v a2s .  c  o 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, "load : 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;
}