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.providers.contacts.ContactsSyncAdapter.java

private static void addGroupMembershipToContactEntry(String account, ContentResolver cr, long personId,
        ContactEntry entry) throws ParseException {
    Cursor c = cr.query(GroupMembership.RAW_CONTENT_URI, null, "person=" + personId, null, null);
    try {//from  w w  w  .j ava2s .co m
        int serverIdIndex = c.getColumnIndexOrThrow(GroupMembership.GROUP_SYNC_ID);
        int localIdIndex = c.getColumnIndexOrThrow(GroupMembership.GROUP_ID);
        while (c.moveToNext()) {
            String serverId = c.getString(serverIdIndex);
            if (serverId == null) {
                final Uri groupUri = ContentUris.withAppendedId(Groups.CONTENT_URI, c.getLong(localIdIndex));
                Cursor groupCursor = cr.query(groupUri, new String[] { Groups._SYNC_ID }, null, null, null);
                try {
                    if (groupCursor.moveToNext()) {
                        serverId = groupCursor.getString(0);
                    }
                } finally {
                    groupCursor.close();
                }
            }
            if (serverId == null) {
                // the group hasn't been synced yet, we can't complete this operation since
                // we don't know what server id to use for the group
                throw new ParseException("unable to construct GroupMembershipInfo since the "
                        + "group _sync_id isn't known yet, will retry later");
            }
            GroupMembershipInfo groupMembershipInfo = new GroupMembershipInfo();
            String groupId = getCanonicalGroupsFeedForAccount(account) + "/" + serverId;
            groupMembershipInfo.setGroup(groupId);
            groupMembershipInfo.setDeleted(false);
            entry.addGroup(groupMembershipInfo);
        }
    } finally {
        if (c != null)
            c.close();
    }
}

From source file:com.hichinaschool.flashcards.libanki.Tags.java

public void bulkAdd(List<Long> ids, String tags, boolean add) {
    List<String> newTags = split(tags);
    if (newTags == null || newTags.isEmpty()) {
        return;//from  w w  w .  ja  v  a 2s . co m
    }
    // cache tag names
    register(newTags);
    // find notes missing the tags
    String l;
    if (add) {
        l = "tags not ";
    } else {
        l = "tags ";
    }
    StringBuilder lim = new StringBuilder();
    for (String t : newTags) {
        if (lim.length() != 0) {
            lim.append(" or ");
        }
        lim.append(l).append("like '% ").append(t).append(" %'");
    }
    Cursor cur = null;
    List<Long> nids = new ArrayList<Long>();
    ArrayList<Object[]> res = new ArrayList<Object[]>();
    try {
        cur = mCol.getDb().getDatabase().rawQuery(
                "select id, tags from notes where id in " + Utils.ids2str(ids) + " and (" + lim + ")", null);
        if (add) {
            while (cur.moveToNext()) {
                nids.add(cur.getLong(0));
                res.add(new Object[] { addToStr(tags, cur.getString(1)), Utils.intNow(), mCol.usn(),
                        cur.getLong(0) });
            }
        } else {
            while (cur.moveToNext()) {
                nids.add(cur.getLong(0));
                res.add(new Object[] { remFromStr(tags, cur.getString(1)), Utils.intNow(), mCol.usn(),
                        cur.getLong(0) });
            }
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    // update tags
    mCol.getDb().executeMany("update notes set tags=:t,mod=:n,usn=:u where id = :id", res);
}

From source file:com.nonninz.robomodel.RoboManager.java

private long getLastId() throws InstanceNotFoundException {
    final SQLiteDatabase db = mDatabaseManager.openOrCreateDatabase(getDatabaseName());

    final String columns[] = new String[] { BaseColumns._ID };
    Cursor query;
    /*/*from  w ww  . j av a2  s .  c om*/
     * Try the query. If the Table doesn't exist, fix the DB and re-run the query.
     */
    try {
        query = db.query(getTableName(), columns, null, null, null, null, null);
    } catch (final SQLiteException e) {
        prepareTable(db);
        query = db.query(getTableName(), columns, null, null, null, null, null);
    }

    if (query.moveToLast()) {
        final int columnIndex = query.getColumnIndex(BaseColumns._ID);
        return query.getLong(columnIndex);
    } else {
        throw new InstanceNotFoundException("table " + getTableName() + " is empty");
    }
}

From source file:com.android.contacts.list.ContactEntryListAdapter.java

protected Uri getContactUri(int partitionIndex, Cursor cursor, int contactIdColumn, int lookUpKeyColumn) {
    long contactId = cursor.getLong(contactIdColumn);
    String lookupKey = cursor.getString(lookUpKeyColumn);
    Uri uri = Contacts.getLookupUri(contactId, lookupKey);
    long directoryId = ((DirectoryPartition) getPartition(partitionIndex)).getDirectoryId();
    if (directoryId != Directory.DEFAULT) {
        uri = uri.buildUpon()/*  w  w w.  j a  v a  2s  .c  o  m*/
                .appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY, String.valueOf(directoryId))
                .build();
    }
    return uri;
}

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

public long objIdForHash(long hash) {
    Cursor c = getReadableDatabase().query(ItemObject.TABLE, new String[] { ItemObject._ID },
            ItemObject.OBJHASH + "= ?", new String[] { String.valueOf(hash) }, null, null, null);
    try {/*ww  w  . j av  a2 s  .c  o  m*/
        if (c.moveToFirst()) {
            return c.getLong(0);
        }
        return -1;
    } finally {
        c.close();
    }
}

From source file:com.example.fcp.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
 * @param lon             the longitude of the city
 * @return the row ID of the added location.
 *///w w  w  . ja  v a2 s.c  o m
long addLocation(String locationSetting, String cityName, double lat, double lon) {
    long locationId;
    // Students: First, check if the location with this city name exists in the db
    Cursor weaCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, null,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + "= ?", new String[] { locationSetting },
            null);

    // If it exists, return the current ID
    if (weaCursor.moveToFirst()) {
        int locationIdIndex = weaCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = weaCursor.getLong(locationIdIndex);
    } else {
        // Otherwise, insert it using the content resolver and the base URI
        ContentValues locValues = new ContentValues();
        locValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        locValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        //long rowId = weaProvider.insert(WeatherContract.LocationEntry.CONTENT_URI,locValues);
        Uri retUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI, locValues);
        //locationId = Long.parseLong(retUri.getLastPathSegment());
        locationId = ContentUris.parseId(retUri);
    }
    return locationId;
}

From source file:com.example.mihai.inforoute.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  ww. j  a  v a 2s  . 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) {
    long locationId;

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

    if (locationCursor.moveToFirst()) {
        int locationIdIndex = locationCursor.getColumnIndex(RouteContract.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(RouteContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(RouteContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(RouteContract.LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(RouteContract.LocationEntry.COLUMN_COORD_LONG, lon);

        // Finally, insert location data into the database.
        Uri insertedUri = mContext.getContentResolver().insert(RouteContract.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();
    return locationId;
}

From source file:com.borqs.browser.combo.BookmarksPageCallbacks.java

private void displayRemoveBookmarkDialog(BrowserBookmarksAdapter adapter, int position) {
    // Put up a dialog asking if the user really wants to
    // delete the bookmark
    Cursor cursor = adapter.getItem(position);
    long id = cursor.getLong(BookmarksLoader.COLUMN_INDEX_ID);
    String title = cursor.getString(BookmarksLoader.COLUMN_INDEX_TITLE);
    Context context = this;
    BookmarkUtils.displayRemoveBookmarkDialog(id, title, context, null);
}

From source file:com.example.debra.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  ww  . j a v  a2  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
    long locationId;
    Cursor cursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? ", new String[] { locationSetting },
            null);
    if (cursor.moveToFirst()) {
        locationId = cursor.getLong(cursor.getColumnIndex(WeatherContract.LocationEntry._ID));
    } else {
        ContentValues value = new ContentValues();
        value.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        value.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        value.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        value.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        Uri insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                value);
        locationId = ContentUris.parseId(insertedUri);
    }
    cursor.close();
    return locationId;
}

From source file:com.textuality.lifesaver.Columns.java

public JSONObject cursorToJSON(Cursor cursor) {
    setColumns(cursor);//from www  . ja  v  a 2 s .c  o  m
    JSONObject json = new JSONObject();
    try {
        for (int i = 0; i < names.length; i++) {
            int col = columns[i];
            if (cursor.isNull(col))
                continue;
            switch (types[i]) {
            case STRING:
                json.put(names[i], cursor.getString(col));
                break;
            case INT:
                json.put(names[i], cursor.getInt(col));
                break;
            case LONG:
                json.put(names[i], cursor.getLong(col));
                break;
            case FLOAT:
                json.put(names[i], cursor.getFloat(col));
                break;
            case DOUBLE:
                json.put(names[i], cursor.getDouble(col));
                break;
            }
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

    return json;
}