Example usage for android.database.sqlite SQLiteQueryBuilder buildQueryString

List of usage examples for android.database.sqlite SQLiteQueryBuilder buildQueryString

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteQueryBuilder buildQueryString.

Prototype

public static String buildQueryString(boolean distinct, String tables, String[] columns, String where,
        String groupBy, String having, String orderBy, String limit) 

Source Link

Document

Build an SQL query string from the given clauses.

Usage

From source file:Main.java

public static int getRowCount(SQLiteDatabase db, boolean distinct, String table, String[] columns,
        String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) {
    if (columns != null && columns.length > 0) {
        columns = new String[] { columns[0] };
    }//from w ww .  jav  a 2 s  .  co  m
    String sql = SQLiteQueryBuilder.buildQueryString(distinct, table, columns, selection, groupBy, having,
            orderBy, limit);
    String countSelection = "SELECT count(*) FROM (" + sql + ")";
    return (int) DatabaseUtils.longForQuery(db, countSelection, selectionArgs);
}

From source file:com.gvccracing.android.tttimer.Tabs.RaceInfoTab.java

public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    Log.i(LOG_TAG(), "onCreateLoader start: id=" + Integer.toString(id));
    CursorLoader loader = null;//w w w .  ja v a  2  s  .  c  om
    String[] projection;
    String selection;
    String[] selectionArgs = null;
    String sortOrder;
    switch (id) {
    case RACE_INFO_LOADER:
        projection = new String[] { Race.Instance().getTableName() + "." + Race._ID + " as _id", Race.RaceDate,
                RaceLocation.CourseName, Race.RaceType, Race.StartInterval, RaceLocation.Distance,
                Race.NumLaps };
        selection = Race.Instance().getTableName() + "." + Race._ID + "="
                + AppSettings.Instance().getParameterSql(AppSettings.AppSetting_RaceID_Name);
        selectionArgs = null;
        sortOrder = Race.Instance().getTableName() + "." + Race._ID;
        loader = new CursorLoader(getActivity(), RaceInfoView.Instance().CONTENT_URI, projection, selection,
                selectionArgs, sortOrder);
        break;
    case APP_SETTINGS_LOADER_RACEINFO:
        projection = new String[] { AppSettings.AppSettingName, AppSettings.AppSettingValue };
        selection = null;
        sortOrder = null;
        selectionArgs = null;
        loader = new CursorLoader(getActivity(), AppSettings.Instance().CONTENT_URI, projection, selection,
                selectionArgs, sortOrder);
        break;
    case COURSE_RECORD_LOADER:
        projection = new String[] { RaceResults.Instance().getTableName() + "." + RaceResults._ID + " as _id",
                RaceResults.ElapsedTime };
        selection = Race.Instance().getTableName() + "." + Race.RaceLocation_ID + " in ("
                + SQLiteQueryBuilder.buildQueryString(true, RaceInfoView.Instance().getTableName(),
                        new String[] { Race.RaceLocation_ID },
                        Race.Instance().getTableName() + "." + Race._ID + "="
                                + AppSettings.Instance().getParameterSql(AppSettings.AppSetting_RaceID_Name),
                        null, null, Race.Instance().getTableName() + "." + Race._ID, "1")
                + ")";
        selectionArgs = null;
        sortOrder = RaceResults.Instance().getTableName() + "." + RaceResults.ElapsedTime;
        loader = new CursorLoader(getActivity(), RaceInfoResultsView.Instance().CONTENT_URI, projection,
                selection, selectionArgs, sortOrder);
        break;
    }
    Log.i(LOG_TAG(), "onCreateLoader complete: id=" + Integer.toString(id));
    return loader;
}

From source file:com.android.quicksearchbox.ShortcutRepositoryImplLog.java

private void buildShortcutQueries() {
    // SQL expression for the time before which no clicks should be counted.
    String cutOffTime_expr = "(?3 - " + mConfig.getMaxStatAgeMillis() + ")";
    // Filter out clicks that are too old
    String ageRestriction = ClickLog.hit_time.fullName + " >= " + cutOffTime_expr;
    String having = null;//from   w ww .  jav a  2  s .  co  m
    // Order by sum of hit times (seconds since cutoff) for the clicks for each shortcut.
    // This has the effect of multiplying the average hit time with the click count
    String ordering_expr = "SUM((" + ClickLog.hit_time.fullName + " - " + cutOffTime_expr + ") / 1000)";

    String where = ageRestriction;
    String preferLatest = PREFER_LATEST_PREFIX + where + PREFER_LATEST_SUFFIX;
    String orderBy = preferLatest + " DESC, " + ordering_expr + " DESC";
    mEmptyQueryShortcutQuery = SQLiteQueryBuilder.buildQueryString(false, TABLES, SHORTCUT_QUERY_COLUMNS, where,
            GROUP_BY, having, orderBy, null);
    if (DBG)
        Log.d(TAG, "Empty shortcut query:\n" + mEmptyQueryShortcutQuery);

    where = PREFIX_RESTRICTION + " AND " + ageRestriction;
    preferLatest = PREFER_LATEST_PREFIX + where + PREFER_LATEST_SUFFIX;
    orderBy = preferLatest + " DESC, " + ordering_expr + " DESC";
    mShortcutQuery = SQLiteQueryBuilder.buildQueryString(false, TABLES, SHORTCUT_QUERY_COLUMNS, where, GROUP_BY,
            having, orderBy, null);
    if (DBG)
        Log.d(TAG, "Empty shortcut:\n" + mShortcutQuery);
}

From source file:com.android.quicksearchbox.ShortcutRepositoryImplLog.java

/**
 * @return sql that ranks sources by total clicks, filtering out sources
 *         without enough clicks.// w  w  w  . j  a  v  a2 s  .  c o  m
 */
private static String buildSourceRankingSql() {
    final String orderingExpr = SourceStats.total_clicks.name();
    final String tables = SourceStats.TABLE_NAME;
    final String[] columns = SourceStats.COLUMNS;
    final String where = SourceStats.total_clicks + " >= $1";
    final String groupBy = null;
    final String having = null;
    final String orderBy = orderingExpr + " DESC";
    final String limit = null;
    return SQLiteQueryBuilder.buildQueryString(false, tables, columns, where, groupBy, having, orderBy, limit);
}

From source file:pl.ipebk.tabi.infrastructure.daos.SearchHistoryDao.java

/**
 * Gets count of places that are not special and that has own plates
 *///from   ww  w. j a  va  2s .c om
int getStandardPlacesWithPlateCount() {
    String[] columns = { "count(1)" };
    String whereClause = PlacesTable.COLUMN_PLACE_TYPE + " < ? AND " + PlacesTable.COLUMN_HAS_OWN_PLATE
            + " = ? ";
    String[] whereArgs = { Integer.toString(PlaceType.SPECIAL.ordinal()), Integer.toString(1) };

    String sql = SQLiteQueryBuilder.buildQueryString(false, PlacesTable.TABLE_NAME, columns, whereClause, null,
            null, null, null);
    Cursor cursor = db.query(sql, whereArgs);

    return getSimpleInt(cursor);
}

From source file:pl.ipebk.tabi.infrastructure.daos.SearchHistoryDao.java

/**
 * Gets count of places that are not special
 *//*from  www .  j av  a 2 s .c  om*/
int getPlacesCount() {
    String[] columns = { "count(1)" };
    String whereClause = PlacesTable.COLUMN_PLACE_TYPE + " < ? ";
    String[] whereArgs = { Integer.toString(PlaceType.SPECIAL.ordinal()) };
    String sql = SQLiteQueryBuilder.buildQueryString(false, PlacesTable.TABLE_NAME, columns, whereClause, null,
            null, null, null);
    Cursor cursor = db.query(sql, whereArgs);

    return getSimpleInt(cursor);
}

From source file:info.wncwaterfalls.app.ResultsActivity.java

@Override
public Bundle onWaterfallQuery() {
    // Set up our query
    ArrayList<String> whereList = new ArrayList<String>(); // To hold chunks of the WHERE clause
    ArrayList<String> argList = new ArrayList<String>(); // To hold our args
    switch (mSearchMode) {
    // See which terms we're going to need to query           
    case SearchActivity.SEARCH_MODE_WATERFALL:
        whereList.add("name like ?");
        argList.add('%' + searchTerm.trim() + '%');
        break;//  w  ww  . j a v a2s . c  om

    case SearchActivity.SEARCH_MODE_HIKE:
        whereList.add("trail_length <= ?");
        argList.add(String.valueOf(searchTrailLength));

        whereList.add("trail_difficulty_num <= ?");
        argList.add(String.valueOf(searchTrailDifficulty));

        whereList.add("trail_climb_num <= ?");
        argList.add(String.valueOf(searchTrailClimb));

        break;

    case SearchActivity.SEARCH_MODE_LOCATION:
        if (mFoundOrigin) {
            // Mi -> M
            double rangeMeters = searchLocationDistance * 1609.34;

            // Calculate our bounding box
            Location pn = calculatePositionAtRange(mOriginLocation, rangeMeters, 0);
            Location pe = calculatePositionAtRange(mOriginLocation, rangeMeters, 90);
            Location ps = calculatePositionAtRange(mOriginLocation, rangeMeters, 180);
            Location pw = calculatePositionAtRange(mOriginLocation, rangeMeters, 270);

            // Greater than S latitude
            whereList.add("geo_lat > ?");
            argList.add(String.valueOf(ps.getLatitude()));

            // Less than N latitude
            whereList.add("geo_lat < ?");
            argList.add(String.valueOf(pn.getLatitude()));

            // Less than E longitude
            whereList.add("geo_lon < ?");
            argList.add(String.valueOf(pe.getLongitude()));

            // Greater than W longitude
            whereList.add("geo_lon > ?");
            argList.add(String.valueOf(pw.getLongitude()));
        } else {
            // Make sure no results are returned, and a toast should happen
            // on the map side notifying the user as such.
            whereList.add("_id = ?");
            argList.add("");
        }

        // Requester can filter results to actual radius using 
        // android.location.Location.distanceTo()
        break;
    }

    // Restrict to only shared falls if box checked
    if (searchOnlyShared != null && searchOnlyShared) {
        whereList.add("shared=1");
    }

    String tables = "waterfalls";

    // Select all
    String[] columns = AttrDatabase.COLUMNS.toArray(new String[AttrDatabase.COLUMNS.size()]);

    String and = " AND "; // To join our where clause
    String whereClause = TextUtils.join(and, whereList);

    String query = SQLiteQueryBuilder.buildQueryString(false, tables, columns, whereClause, null, null,
            "name ASC", null);

    Bundle qBundle = new Bundle();
    qBundle.putString("query", query);
    String[] args = argList.toArray(new String[argList.size()]);
    qBundle.putStringArray("args", args);
    return qBundle;
}