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.android.dialer.calllog.ContactInfoHelper.java

/**
 * Looks up a contact using the given URI.
 * <p>/*from  www  .  j  a va 2 s .co  m*/
 * It returns null if an error occurs, {@link ContactInfo#EMPTY} if no matching contact is
 * found, or the {@link ContactInfo} for the given contact.
 * <p>
 * The {@link ContactInfo#formattedNumber} field is always set to {@code null} in the returned
 * value.
 */
private ContactInfo lookupContactFromUri(Uri uri) {
    if (uri == null) {
        return null;
    }
    if (!PermissionsUtil.hasContactsPermissions(mContext)) {
        return ContactInfo.EMPTY;
    }
    final ContactInfo info;
    Cursor phonesCursor = mContext.getContentResolver().query(uri, PhoneQuery._PROJECTION, null, null, null);

    if (phonesCursor != null) {
        try {
            if (phonesCursor.moveToFirst()) {
                info = new ContactInfo();
                long contactId = phonesCursor.getLong(PhoneQuery.PERSON_ID);
                String lookupKey = phonesCursor.getString(PhoneQuery.LOOKUP_KEY);
                info.lookupKey = lookupKey;
                info.lookupUri = Contacts.getLookupUri(contactId, lookupKey);
                info.name = phonesCursor.getString(PhoneQuery.NAME);
                info.type = phonesCursor.getInt(PhoneQuery.PHONE_TYPE);
                info.label = phonesCursor.getString(PhoneQuery.LABEL);
                info.number = phonesCursor.getString(PhoneQuery.MATCHED_NUMBER);
                info.normalizedNumber = phonesCursor.getString(PhoneQuery.NORMALIZED_NUMBER);
                info.photoId = phonesCursor.getLong(PhoneQuery.PHOTO_ID);
                info.photoUri = UriUtils.parseUriOrNull(phonesCursor.getString(PhoneQuery.PHOTO_URI));
                info.formattedNumber = null;
            } else {
                info = ContactInfo.EMPTY;
            }
        } finally {
            phonesCursor.close();
        }
    } else {
        // Failed to fetch the data, ignore this request.
        info = null;
    }
    return info;
}

From source file:com.prashantpal.sunshine.app.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 ww  w.j ava 2  s .  c  o m
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
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
    long locationId;
    ContentResolver resolver = mContext.getContentResolver();
    Cursor cursor = resolver.query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + "= ?", new String[] { locationSetting },
            null);
    if (cursor.moveToFirst()) {
        int locationIdIndex = cursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = cursor.getLong(locationIdIndex);
    } else {
        ContentValues contentValues = new ContentValues();
        contentValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        Uri uri = resolver.insert(WeatherContract.LocationEntry.CONTENT_URI, contentValues);
        locationId = ContentUris.parseId(uri);
    }
    cursor.close();
    // Otherwise, insert it using the content resolver and the base URI
    return locationId;
}

From source file:com.waageweb.sunshine.app.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 .  j  a v  a 2 s .com
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
long addLocation(String locationSetting, String cityName, double lat, double lon) {
    // Students: 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);

    if (locationCursor.moveToFirst()) {
        // If it exists, return the current ID
        return locationCursor.getLong(locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID));
    } else {
        ContentValues contentValues = new ContentValues();
        contentValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, "" + lat);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, "" + lon);

        Uri uriInserted = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                contentValues);

        // Otherwise, insert it using the content resolver and the base URI
        return ContentUris.parseId(uriInserted);
    }
}

From source file:com.ichi2.libanki.Note.java

public void load() {
    Cursor cursor = null;
    try {//ww  w .j  a v a  2  s . c om
        cursor = mCol.getDb().getDatabase().rawQuery(
                "SELECT guid, mid, mod, usn, tags, flds, flags, data FROM notes WHERE id = " + mId, null);
        if (!cursor.moveToFirst()) {
            throw new RuntimeException("Notes.load(): No result from query for note " + mId);
        }
        mGuId = cursor.getString(0);
        mMid = cursor.getLong(1);
        mMod = cursor.getLong(2);
        mUsn = cursor.getInt(3);
        mTags = mCol.getTags().split(cursor.getString(4));
        mFields = Utils.splitFields(cursor.getString(5));
        mFlags = cursor.getInt(6);
        mData = cursor.getString(7);
        mModel = mCol.getModels().get(mMid);
        mFMap = mCol.getModels().fieldMap(mModel);
        mScm = mCol.getScm();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:mobisocial.bento.anyshare.util.DBHelper.java

public synchronized long getNextId() {
    if (mNextId == -1) {
        Cursor c = getReadableDatabase().query(ItemObject.TABLE, new String[] { "MAX(" + ItemObject._ID + ")" },
                null, null, null, null, null);
        try {/* w  ww .  j av a2 s .  c om*/
            if (c.moveToFirst()) {
                mNextId = c.getLong(0) + 1;
            }
        } finally {
            c.close();
        }
    }
    return mNextId++;
}

From source file:com.arminkale.android.sunshine.app.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//ww  w .  j  a v  a2s.  co  m
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
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

    long locationId;
    // First, check if the location with this city name exists in the db
    Cursor locationCursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI,
            new String[] { LocationEntry._ID }, LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
            new String[] { locationSetting }, null);

    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(LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(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);
    }

    // Close the cursor and return the new ID.
    locationCursor.close();
    return locationId;
}

From source file:edu.mit.mobile.android.locast.data.CastMedia.java

/**
 * @param context//from ww w  .  java2 s .  co m
 * @param c
 * @param castMediaUri
 *
 */
public static void showMedia(Context context, Cursor c, Uri castMediaUri) {
    final String mediaString = c.getString(c.getColumnIndex(CastMedia._MEDIA_URL));
    final String locMediaString = c.getString(c.getColumnIndex(CastMedia._LOCAL_URI));
    String mimeType = null;

    Uri media;

    if (locMediaString != null) {
        media = Uri.parse(locMediaString);
        if ("file".equals(media.getScheme())) {
            mimeType = c.getString(c.getColumnIndex(CastMedia._MIME_TYPE));
        }

    } else if (mediaString != null) {
        media = Uri.parse(mediaString);
        mimeType = c.getString(c.getColumnIndex(CastMedia._MIME_TYPE));

        // we strip this because we don't really want to force them to go to the browser.
        if ("text/html".equals(mimeType)) {
            mimeType = null;
        }
    } else {
        Log.e(TAG, "asked to show media for " + castMediaUri + " but there was nothing to show");
        return;
    }

    final Intent i = new Intent(Intent.ACTION_VIEW);
    i.setDataAndType(media, mimeType);

    if (mimeType != null && mimeType.startsWith("video/")) {
        context.startActivity(new Intent(Intent.ACTION_VIEW,
                ContentUris.withAppendedId(castMediaUri, c.getLong(c.getColumnIndex(CastMedia._ID)))));
    } else {
        // setting the MIME type for URLs doesn't work.
        try {
            context.startActivity(i);
        } catch (final ActivityNotFoundException e) {
            // try it again, but without a mime type.
            if (mimeType != null) {
                i.setDataAndType(media, null);
            }
            try {
                context.startActivity(i);
            } catch (final ActivityNotFoundException e2) {
                Toast.makeText(context, R.string.error_cast_media_no_activities, Toast.LENGTH_LONG).show();
            }
        }
    }
}

From source file:ceruleanotter.github.com.sunshine.FetchWeatherTask.java

private long insertLocationInDatabase(String locationSetting, String cityName, double lat, double lon) {

    Log.v(LOG_TAG, "inserting " + cityName + ", with coord: " + lat + ", " + lon);

    // First, check if the location with this city name exists in the db
    Cursor cursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI,
            new String[] { LocationEntry._ID }, LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
            new String[] { locationSetting }, null);

    if (cursor.moveToFirst()) {
        Log.v(LOG_TAG, "Found it in the database!");
        int locationIdIndex = cursor.getColumnIndex(LocationEntry._ID);
        return cursor.getLong(locationIdIndex);
    } else {//from w w  w .ja va2  s .  c  o  m
        Log.v(LOG_TAG, "Didn't find it in the database, inserting now!");
        ContentValues locationValues = new ContentValues();
        locationValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(LocationEntry.COLUMN_COORD_LONG, lon);

        Uri locationInsertUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, locationValues);

        return ContentUris.parseId(locationInsertUri);
    }
}

From source file:com.home883.ali.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  ww . jav  a 2  s . c  o  m*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
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

    Cursor locationCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, null,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting },
            null);

    long locationRow;

    if (locationCursor.moveToFirst()) {
        locationRow = locationCursor.getLong(locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID));
    } else {
        ContentValues values = new ContentValues();
        values.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        values.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        Uri locationUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                values);
        locationRow = ContentUris.parseId(locationUri);
    }

    return locationRow;
}

From source file:com.granita.contacticloudsync.resource.LocalCalendar.java

@SuppressWarnings("Recycle")
public void processDirtyExceptions() throws CalendarStorageException {
    // process deleted exceptions
    Constants.log.info("Processing deleted exceptions");
    try {/*from   w  w  w  .  j  av a  2  s . c o m*/
        @Cleanup
        Cursor cursor = provider.query(syncAdapterURI(Events.CONTENT_URI),
                new String[] { Events._ID, Events.ORIGINAL_ID, LocalEvent.COLUMN_SEQUENCE },
                Events.DELETED + "!=0 AND " + Events.ORIGINAL_ID + " IS NOT NULL", null, null);
        while (cursor != null && cursor.moveToNext()) {
            Constants.log.debug("Found deleted exception, removing; then re-schuling original event");
            long id = cursor.getLong(0), // can't be null (by definition)
                    originalID = cursor.getLong(1); // can't be null (by query)
            int sequence = cursor.isNull(2) ? 0 : cursor.getInt(2);

            // get original event's SEQUENCE
            @Cleanup
            Cursor cursor2 = provider.query(
                    syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, originalID)),
                    new String[] { LocalEvent.COLUMN_SEQUENCE }, null, null, null);
            int originalSequence = cursor.isNull(0) ? 0 : cursor.getInt(0);

            BatchOperation batch = new BatchOperation(provider);
            // re-schedule original event and set it to DIRTY
            batch.enqueue(ContentProviderOperation
                    .newUpdate(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, originalID)))
                    .withValue(LocalEvent.COLUMN_SEQUENCE, originalSequence)
                    .withValue(Events.DIRTY, DIRTY_INCREASE_SEQUENCE).build());
            // remove exception
            batch.enqueue(ContentProviderOperation
                    .newDelete(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, id))).build());
            batch.commit();
        }
    } catch (RemoteException e) {
        throw new CalendarStorageException("Couldn't process locally modified exception", e);
    }

    // process dirty exceptions
    Constants.log.info("Processing dirty exceptions");
    try {
        @Cleanup
        Cursor cursor = provider.query(syncAdapterURI(Events.CONTENT_URI),
                new String[] { Events._ID, Events.ORIGINAL_ID, LocalEvent.COLUMN_SEQUENCE },
                Events.DIRTY + "!=0 AND " + Events.ORIGINAL_ID + " IS NOT NULL", null, null);
        while (cursor != null && cursor.moveToNext()) {
            Constants.log.debug("Found dirty exception, increasing SEQUENCE to re-schedule");
            long id = cursor.getLong(0), // can't be null (by definition)
                    originalID = cursor.getLong(1); // can't be null (by query)
            int sequence = cursor.isNull(2) ? 0 : cursor.getInt(2);

            BatchOperation batch = new BatchOperation(provider);
            // original event to DIRTY
            batch.enqueue(ContentProviderOperation
                    .newUpdate(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, originalID)))
                    .withValue(Events.DIRTY, DIRTY_DONT_INCREASE_SEQUENCE).build());
            // increase SEQUENCE and set DIRTY to 0
            batch.enqueue(ContentProviderOperation
                    .newUpdate(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, id)))
                    .withValue(LocalEvent.COLUMN_SEQUENCE, sequence + 1).withValue(Events.DIRTY, 0).build());
            batch.commit();
        }
    } catch (RemoteException e) {
        throw new CalendarStorageException("Couldn't process locally modified exception", e);
    }
}