Example usage for android.database.sqlite SQLiteDatabase query

List of usage examples for android.database.sqlite SQLiteDatabase query

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase query.

Prototype

public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy,
        String having, String orderBy) 

Source Link

Document

Query the given table, returning a Cursor over the result set.

Usage

From source file:com.google.zxing.client.android.history.HistoryManager.java

/**
 * <p>/*from www. j a  v  a 2  s  . c  om*/
 * Builds a text representation of the scanning history. Each scan is
 * encoded on one line, terminated by a line break (\r\n). The values in
 * each line are comma-separated, and double-quoted. Double-quotes within
 * values are escaped with a sequence of two double-quotes. The fields
 * output are:
 * </p>
 * 
 * <ul>
 * <li>Raw text</li>
 * <li>Display text</li>
 * <li>Format (e.g. QR_CODE)</li>
 * <li>Timestamp</li>
 * <li>Formatted version of timestamp</li>
 * </ul>
 */
CharSequence buildHistory() {
    SQLiteOpenHelper helper = new DBHelper(activity);
    SQLiteDatabase db = null;
    Cursor cursor = null;
    try {
        db = helper.getWritableDatabase();
        cursor = db.query(DBHelper.TABLE_NAME, COLUMNS, null, null, null, null,
                DBHelper.TIMESTAMP_COL + " DESC");

        StringBuilder historyText = new StringBuilder(1000);
        while (cursor.moveToNext()) {

            historyText.append('"').append(massageHistoryField(cursor.getString(0))).append("\",");
            historyText.append('"').append(massageHistoryField(cursor.getString(1))).append("\",");
            historyText.append('"').append(massageHistoryField(cursor.getString(2))).append("\",");
            historyText.append('"').append(massageHistoryField(cursor.getString(3))).append("\",");

            // Add timestamp again, formatted
            long timestamp = cursor.getLong(3);
            historyText.append('"')
                    .append(massageHistoryField(EXPORT_DATE_TIME_FORMAT.format(new Date(timestamp))))
                    .append("\",");

            // Above we're preserving the old ordering of columns which had
            // formatted data in position 5

            historyText.append('"').append(massageHistoryField(cursor.getString(4))).append("\"\r\n");
        }
        return historyText;
    } finally {
        close(cursor, db);
    }
}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public String getOnline(String buddyId) {
    int index = buddyId.indexOf('@');
    if (index >= 0) {
        buddyId = buddyId.substring(0, index);
    }/*w w w .  j a  v  a2  s  .c o m*/
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    Cursor c = db.query(MessageHistoryContract.ChatEntry.TABLE_NAME_ALL_CHATS,
            new String[] { MessageHistoryContract.ChatEntry.COLUMN_NAME_LAST_ONLINE },
            MessageHistoryContract.ChatEntry.COLUMN_NAME_BUDDY_ID + "=?", new String[] { buddyId }, null, null,
            null);
    String result = null;
    try {
        c.moveToFirst();
        if (c.getCount() > 0)
            result = c.getString(0);
    } catch (Exception e) {
        e.printStackTrace();
    }
    c.close();
    db.close();
    return result;
}

From source file:com.citrus.sdk.database.DBHandler.java

public List<OptionDetails> getSavedOptions() {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor current_cursor;//from   w  w w  . j  a  v a  2s. c  o m
    String[] columNames = { MMID, SCHEME, EXPDATE, NAME, OWNER, BANK, NUMBER, TYPE, IMPS_REGISTERED, TOKEN_ID,
            DEFAULT_OPTION };
    String orderBy = DEFAULT_OPTION + " DESC";
    List<OptionDetails> savedOptions = new ArrayList<OptionDetails>();
    current_cursor = db.query(PAYOPTION_TABLE, columNames, null, null, null, null, orderBy);
    if (current_cursor.moveToFirst()) {
        do {
            OptionDetails currentOption = new OptionDetails(current_cursor);
            savedOptions.add(currentOption);
        } while (current_cursor.moveToNext());
    }
    return savedOptions;
}

From source file:org.pixmob.freemobile.netstat.SyncService.java

private String getDeviceId() {
    final SQLiteDatabase db = dbHelper.getWritableDatabase();
    final Cursor c = db.query("device", new String[] { "device_id" }, null, null, null, null, null);
    String deviceId = null;/*from  w  w w  .j a va 2s  . c om*/
    try {
        if (c.moveToNext()) {
            deviceId = c.getString(0);
        }
    } finally {
        c.close();
    }
    if (deviceId == null) {
        // Generate a new device identifier.
        deviceId = UUID.randomUUID().toString();

        // Store this device identifier in the database.
        final ContentValues cv = new ContentValues(1);
        cv.put("device_id", deviceId);
        db.insertOrThrow("device", null, cv);
    }
    return deviceId;
}

From source file:cn.edu.wyu.documentviewer.RecentsProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    final SQLiteDatabase db = mHelper.getReadableDatabase();
    switch (sMatcher.match(uri)) {
    case URI_RECENT:
        final long cutoff = System.currentTimeMillis() - MAX_HISTORY_IN_MILLIS;
        return db.query(TABLE_RECENT, projection, RecentColumns.TIMESTAMP + ">" + cutoff, null, null, null,
                sortOrder);// ww w. j  a  v a  2 s  .  com
    case URI_STATE:
        final String authority = uri.getPathSegments().get(1);
        final String rootId = uri.getPathSegments().get(2);
        final String documentId = uri.getPathSegments().get(3);
        return db.query(
                TABLE_STATE, projection, StateColumns.AUTHORITY + "=? AND " + StateColumns.ROOT_ID + "=? AND "
                        + StateColumns.DOCUMENT_ID + "=?",
                new String[] { authority, rootId, documentId }, null, null, sortOrder);
    case URI_RESUME:
        final String packageName = uri.getPathSegments().get(1);
        return db.query(TABLE_RESUME, projection, ResumeColumns.PACKAGE_NAME + "=?",
                new String[] { packageName }, null, null, sortOrder);
    default:
        throw new UnsupportedOperationException("Unsupported Uri " + uri);
    }
}

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 www . j a  v  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.nonninz.robomodel.RoboManager.java

public long[] getSelectedModelIds(String selection, String[] selectionArgs, String groupBy, String having,
        String orderBy) {//from w w  w  .j  a va 2 s . c  om
    final SQLiteDatabase db = mDatabaseManager.openOrCreateDatabase(getDatabaseName());

    final String columns[] = new String[] { BaseColumns._ID };
    Cursor query;

    /*
     * Try the query. If the Table doesn't exist, fix the DB and re-run the query.
     */
    try {
        query = db.query(getTableName(), columns, selection, selectionArgs, groupBy, having, orderBy);
    } catch (final SQLiteException e) {
        prepareTable(db);
        query = db.query(getTableName(), columns, selection, selectionArgs, groupBy, having, orderBy);
    }

    final int columnIndex = query.getColumnIndex(BaseColumns._ID);
    final long result[] = new long[query.getCount()];
    for (query.moveToFirst(); !query.isAfterLast(); query.moveToNext()) {
        result[query.getPosition()] = query.getLong(columnIndex);
    }

    return result;
}

From source file:com.teinvdlugt.android.greekgods.AllPeopleActivity.java

private void refresh() {
    new AsyncTask<Void, Void, List<Person>>() {
        @Override// w w w.j  ava2  s . c o m
        protected List<Person> doInBackground(Void... params) {
            if (searchQuery == null)
                searchQuery = "";

            List<Person> result = new ArrayList<>();

            SQLiteDatabase db = null;
            Cursor c = null;
            try {
                db = openOrCreateDatabase("data", 0, null);
                String[] columns = { "personId", "name" };
                String selection = "name LIKE '" + searchQuery + "%'";
                c = db.query("people", columns, selection, null, null, null, "name");
                int idColumn = c.getColumnIndex("personId");
                int nameColumn = c.getColumnIndex("name");

                c.moveToFirst();
                do {
                    Person p = new Person();
                    p.setId(c.getInt(idColumn));
                    p.setName(c.getString(nameColumn));
                    result.add(p);
                } while (c.moveToNext());
            } catch (SQLiteException e) {
                return null;
            } catch (CursorIndexOutOfBoundsException ignored) {
            } finally {
                if (c != null)
                    c.close();
                if (db != null)
                    db.close();
            }

            return result;
        }

        @Override
        protected void onPostExecute(List<Person> persons) {
            adapter.setData(persons);
        }
    }.execute();
}

From source file:uk.org.rivernile.edinburghbustracker.android.SettingsDatabase.java

/**
 * This method checks to see if a favourite stop already exists in the
 * database.//from w  w w  .  j  av  a  2s.  c o m
 *
 * @param stopCode The stopCode to check for.
 * @return True if it already exists, false if it doesn't.
 */
public boolean getFavouriteStopExists(final String stopCode) {
    if (stopCode == null || stopCode.length() == 0)
        return false;

    final SQLiteDatabase db = getReadableDatabase();
    final Cursor c = db.query(FAVOURITE_STOPS_TABLE, new String[] { FAVOURITE_STOPS_STOPCODE },
            FAVOURITE_STOPS_STOPCODE + " = ?", new String[] { stopCode }, null, null, null);
    if (c.getCount() > 0) {
        c.close();
        return true;
    }

    c.close();
    return false;
}

From source file:uk.org.rivernile.edinburghbustracker.android.SettingsDatabase.java

/**
 * Get the name for a bus stop.//from w  w w  .j  av  a2 s  .  co  m
 *
 * @param stopCode The bus stop code.
 * @return The name for the bus stop.
 */
public String getNameForStop(final String stopCode) {
    if (stopCode == null || stopCode.length() == 0 || !getFavouriteStopExists(stopCode))
        return null;

    final SQLiteDatabase db = getReadableDatabase();
    final Cursor c = db.query(FAVOURITE_STOPS_TABLE, new String[] { FAVOURITE_STOPS_STOPNAME },
            FAVOURITE_STOPS_STOPCODE + " = ?", new String[] { stopCode }, null, null, null);
    String result = null;
    if (c.moveToFirst()) {
        result = c.getString(0);
    }

    c.close();
    return result;
}