Example usage for android.database.sqlite SQLiteQueryBuilder SQLiteQueryBuilder

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

Introduction

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

Prototype

public SQLiteQueryBuilder() 

Source Link

Usage

From source file:com.android.talkback.labeling.LabelProvider.java

/**
 * Queries for a label or multiple labels in the labels database.
 *
 * @param uri The URI representing the type of query to perform:
 *            {@code LABELS_CONTENT_URI} for a subset of all labels,
 *            {@code LABELS_ID_CONTENT_URI} for a specific label, or
 *            {@code PACKAGE_SUMMARY} for a label count per package.
 * @param projection The columns to return.
 * @param selection The WHERE clause for the query.
 * @param selectionArgs The arguments for the WHERE clause of the query.
 * @param sortOrder the ORDER BY clause for the query.
 * @return A cursor representing the data resulting from the query, or]
 *         {@code null} if the query failed to execute.
 */// ww  w  .ja va  2s  .  co  m
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    if (uri == null) {
        LogUtils.log(this, Log.WARN, NULL_URI_FORMAT_STRING);
        return null;
    }

    if (!UserManagerCompat.isUserUnlocked(getContext())) {
        return null;
    }

    final SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(LabelsTable.TABLE_NAME);

    String groupBy = null;

    switch (sUriMatcher.match(uri)) {
    case LABELS:
        if (TextUtils.isEmpty(sortOrder)) {
            sortOrder = LabelsTable.KEY_ID;
        }
        break;
    case LABELS_ID:
        final String labelIdString = uri.getLastPathSegment();
        final int labelId;
        try {
            labelId = Integer.parseInt(labelIdString);
        } catch (NumberFormatException e) {
            LogUtils.log(this, Log.WARN, UNKNOWN_URI_FORMAT_STRING, uri);
            return null;
        }

        final String where = String.format(Locale.ROOT, "%s = %d", LabelsTable.KEY_ID, labelId);
        queryBuilder.appendWhere(where);
        break;
    case PACKAGE_SUMMARY:
        projection = new String[] { LabelsTable.KEY_PACKAGE_NAME, "COUNT(*)" };
        groupBy = LabelsTable.KEY_PACKAGE_NAME;
        sortOrder = LabelsTable.KEY_PACKAGE_NAME;
        break;
    default:
        LogUtils.log(this, Log.WARN, UNKNOWN_URI_FORMAT_STRING, uri);
        return null;
    }

    initializeDatabaseIfNull();

    return queryBuilder.query(mDatabase, projection, selection, selectionArgs, groupBy, null /* having */,
            sortOrder);
}

From source file:com.money.manager.ex.reports.PayeeReportFragment.java

@Override
protected String prepareQuery(String whereClause) {
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    ViewMobileData mobileData = new ViewMobileData(getContext());
    //data to compose builder
    String[] projectionIn = new String[] { ViewMobileData.PAYEEID + " AS _id", ViewMobileData.PAYEEID,
            ViewMobileData.PAYEE, "SUM(" + ViewMobileData.AmountBaseConvRate + ") AS TOTAL" };
    String selection = ViewMobileData.Status + "<>'V' AND " + ViewMobileData.TransactionType
            + " IN ('Withdrawal', 'Deposit')";
    if (!TextUtils.isEmpty(whereClause)) {
        selection += " AND " + whereClause;
    }// ww  w .  j a  v  a  2s .c o  m
    String groupBy = ViewMobileData.PAYEEID + ", " + ViewMobileData.PAYEE;
    String having = null;
    String sortOrder = ViewMobileData.PAYEE;
    String limit = null;
    //compose builder
    builder.setTables(mobileData.getSource());
    //return query
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        return builder.buildQuery(projectionIn, selection, groupBy, having, sortOrder, limit);
    } else {
        return builder.buildQuery(projectionIn, selection, null, groupBy, having, sortOrder, limit);
    }
}

From source file:com.money.manager.ex.budget.BudgetAdapter.java

private String prepareQuery(String whereClause) {
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    ViewMobileData mobileData = new ViewMobileData(getContext());

    //data to compose builder
    String[] projectionIn = new String[] { "ROWID AS _id", ViewMobileData.CATEGID, ViewMobileData.Category,
            ViewMobileData.SubcategID, ViewMobileData.Subcategory,
            "SUM(" + ViewMobileData.AmountBaseConvRate + ") AS TOTAL" };

    String selection = ViewMobileData.Status + "<>'V' AND " + ViewMobileData.TransactionType
            + " IN ('Withdrawal', 'Deposit')";
    if (!TextUtils.isEmpty(whereClause)) {
        selection += " AND " + whereClause;
    }//from w w w .j  a  v  a2  s .co m

    String groupBy = ViewMobileData.CATEGID + ", " + ViewMobileData.Category + ", " + ViewMobileData.SubcategID
            + ", " + ViewMobileData.Subcategory;

    String having = null;
    //        if (!TextUtils.isEmpty(((CategoriesReportActivity) context).mFilter)) {
    //            String filter = ((CategoriesReportActivity) context).mFilter;
    //            if (TransactionTypes.valueOf(filter).equals(TransactionTypes.Withdrawal)) {
    //                having = "SUM(" + ViewMobileData.AmountBaseConvRate + ") < 0";
    //            } else {
    //                having = "SUM(" + ViewMobileData.AmountBaseConvRate + ") > 0";
    //            }
    //        }

    String sortOrder = ViewMobileData.Category + ", " + ViewMobileData.Subcategory;
    String limit = null;

    builder.setTables(mobileData.getSource());

    return builder.buildQuery(projectionIn, selection, groupBy, having, sortOrder, limit);
}

From source file:com.example.android.tvleanback2.data.VideoDatabase.java

/**
 * Performs a database query./*from w ww.j a v  a  2 s .  c  om*/
 *
 * @param selection     The selection clause
 * @param selectionArgs Selection arguments for "?" components in the selection
 * @param columns       The columns to return
 * @return A Cursor over all rows matching the query
 */
private Cursor query(String selection, String[] selectionArgs, String[] columns) {
    /* The SQLiteBuilder provides a map for all possible columns requested to
     * actual columns in the database, creating a simple column alias mechanism
     * by which the ContentProvider does not need to know the real column names
     */
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    builder.setTables(FTS_VIRTUAL_TABLE);
    builder.setProjectionMap(COLUMN_MAP);

    return builder.query(mDatabaseOpenHelper.getReadableDatabase(), columns, selection, selectionArgs, null,
            null, null);
}

From source file:com.example.android.dragonTV.data.VideoDatabase.java

/**
 * Performs a database query./*www  . j ava  2 s .c  o m*/
 *
 * @param selection     The selection clause
 * @param selectionArgs Selection arguments for "?" components in the selection
 * @param columns       The columns to return
 * @return A Cursor over all rows matching the query
 */
private Cursor query(String selection, String[] selectionArgs, String[] columns) {
    /* The SQLiteBuilder provides a map for all possible columns requested to
     * actual columns in the database, creating a simple column alias mechanism
     * by which the ContentProvider does not need to know the real column names
     */
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    builder.setTables(FTS_VIRTUAL_TABLE);
    builder.setProjectionMap(COLUMN_MAP);

    Cursor cursor = new PaginatedCursor(builder.query(mDatabaseOpenHelper.getReadableDatabase(), columns,
            selection, selectionArgs, null, null, null));

    if (cursor == null) {
        return null;
    } else if (!cursor.moveToFirst()) {
        cursor.close();
        return null;
    }
    return cursor;
}

From source file:com.money.manager.ex.reports.CategoriesReportFragment.java

@Override
protected String prepareQuery(String whereClause) {
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    ViewMobileData mobileData = new ViewMobileData(getContext());

    //data to compose builder
    String[] projectionIn = new String[] { "ROWID AS _id", // this does not fetch anything, unfortunately.
            ViewMobileData.CATEGID, ViewMobileData.Category, ViewMobileData.SubcategID,
            ViewMobileData.Subcategory, "SUM(" + ViewMobileData.AmountBaseConvRate + ") AS TOTAL" };

    String selection = ViewMobileData.Status + "<>'V' AND " + ViewMobileData.TransactionType
            + " IN ('Withdrawal', 'Deposit')";
    if (!TextUtils.isEmpty(whereClause)) {
        selection += " AND " + whereClause;
    }// w ww. j  ava 2 s . co m

    String groupBy = ViewMobileData.CATEGID + ", " + ViewMobileData.Category + ", " + ViewMobileData.SubcategID
            + ", " + ViewMobileData.Subcategory;

    String having = null;
    if (!TextUtils.isEmpty(((CategoriesReportActivity) getActivity()).mFilter)) {
        String filter = ((CategoriesReportActivity) getActivity()).mFilter;
        if (TransactionTypes.valueOf(filter).equals(TransactionTypes.Withdrawal)) {
            having = "SUM(" + ViewMobileData.AmountBaseConvRate + ") < 0";
        } else {
            having = "SUM(" + ViewMobileData.AmountBaseConvRate + ") > 0";
        }
    }

    String sortOrder = ViewMobileData.Category + ", " + ViewMobileData.Subcategory;

    //compose builder
    builder.setTables(mobileData.getSource());

    //return query
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        return builder.buildQuery(projectionIn, selection, groupBy, having, sortOrder, null);
    } else {
        return builder.buildQuery(projectionIn, selection, null, groupBy, having, sortOrder, null);
    }
}

From source file:com.money.manager.ex.home.DashboardFragment.java

private String prepareQueryTopWithdrawals() {
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    ViewMobileData mobileData = new ViewMobileData(getContext());
    // data to compose builder
    String[] projectionIn = new String[] { "ROWID AS _id", ViewMobileData.CATEGID, ViewMobileData.Category,
            ViewMobileData.SubcategID, ViewMobileData.Subcategory,
            "SUM(" + ViewMobileData.AmountBaseConvRate + ") AS TOTAL", "COUNT(*) AS NUM" };

    String selection = ViewMobileData.Status + "<>'V' AND " + ViewMobileData.TransactionType
            + " IN ('Withdrawal')" + " AND (julianday(date('now')) - julianday(" + ViewMobileData.Date
            + ") <= 30)";

    String groupBy = ViewMobileData.CATEGID + ", " + ViewMobileData.Category + ", " + ViewMobileData.SubcategID
            + ", " + ViewMobileData.Subcategory;
    String having = "SUM(" + ViewMobileData.AmountBaseConvRate + ") < 0";
    String sortOrder = "ABS(SUM(" + ViewMobileData.AmountBaseConvRate + ")) DESC";
    String limit = "10";
    // compose builder
    builder.setTables(mobileData.getSource());
    // return query
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        return builder.buildQuery(projectionIn, selection, groupBy, having, sortOrder, limit);
    } else {/* w  w  w . j  ava 2s  . c  o  m*/
        return builder.buildQuery(projectionIn, selection, null, groupBy, having, sortOrder, limit);
    }
}

From source file:com.gmail.emerssso.srbase.database.SRContentProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selArgs, String sortOrder) {

    // Using SQLiteQueryBuilder instead of query() method
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

    int uriType = sURIMatcher.match(uri);
    String tableName = "";
    String[] columns;/*from  w ww. j  a  v  a2  s  .  co m*/
    switch (uriType) {
    case SRS:
    case SR_ID:
        tableName = SRTable.TABLE_NAME;
        columns = SRTable.COLUMNS;
        break;
    case DAILIES:
    case DAILY_ID:
        tableName = DailyTable.TABLE_NAME;
        columns = DailyTable.COLUMNS;
        break;
    case PARTS:
    case PART_ID:
        tableName = PartTable.TABLE_NAME;
        columns = PartTable.COLUMNS;
        break;
    default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }

    checkColumns(projection, columns);
    queryBuilder.setTables(tableName);
    if (isIdType(uriType)) {
        queryBuilder.appendWhere("_id =" + uri.getLastPathSegment());
    }

    SQLiteDatabase db = database.getWritableDatabase();
    Cursor cursor = queryBuilder.query(db, projection, selection, selArgs, null, null, sortOrder);
    // make sure that potential listeners are getting notified
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    return cursor;
}

From source file:org.emergent.android.weave.syncadapter.SyncCache.java

private static Cursor query(SQLiteDatabase db, String tableName, String[] projectionin, String whereClause,
        String[] selectionArgs) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables(tableName);//  ww w  .j av  a2  s  .  c  o m
    return qb.query(db, projectionin, whereClause, selectionArgs, null, null, null /* sortOrder */);
}

From source file:com.odoo.support.provider.OContentProvider.java

private Cursor createQuery(Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sort) {/*from  w  w w . j  av  a2  s.  c o  m*/
    reInitModel();
    SQLiteQueryBuilder query = new SQLiteQueryBuilder();
    boolean withAlias = (projection.length < model.projection().length);
    StringBuffer joins = new StringBuffer();
    String base_table = model.getTableName();
    String base_alias = base_table + "_base";
    HashMap<String, String> projectionMap = new HashMap<String, String>();
    List<String> mJoinTables = new ArrayList<String>();
    for (String col_name : projection) {
        String col = col_name;
        if (col_name.contains(".")) {
            col = col_name.split("\\.")[0];
        }
        OColumn column = model.getColumn(col);
        String display_col = col;
        if (withAlias) {
            display_col = base_alias + "." + col + " AS " + col;
            boolean many2oneJoin = col_name.contains(".");
            if (column.getRelationType() != null && many2oneJoin) {
                OModel rel_model = model.createInstance(column.getType());
                String table = rel_model.getTableName();
                String alias = table;
                alias = table + "_self";
                table += " AS " + alias;
                if (!mJoinTables.contains(alias)) {
                    mJoinTables.add(alias);
                    joins.append(" JOIN ");
                    joins.append(table);
                    joins.append(" ON ");
                    joins.append(base_alias + "." + column.getName());
                    joins.append(" = ");
                    joins.append(alias + "." + OColumn.ROW_ID);
                    joins.append(" ");
                }
                String rel_col = col;
                String rel_col_name = "";
                if (col_name.contains(".")) {
                    rel_col += "_" + col_name.split("\\.")[1];
                    rel_col_name = col_name.split("\\.")[1];
                }
                projectionMap.put(rel_col, alias + "." + rel_col_name + " AS " + rel_col);
            }
        }
        projectionMap.put(col, display_col);
    }
    StringBuffer tables = new StringBuffer();
    tables.append(base_table + ((withAlias) ? " AS " + base_alias : " "));
    tables.append(joins.toString());
    query.setTables(tables.toString());
    query.setProjectionMap(projectionMap);
    StringBuffer whr = new StringBuffer();
    String where = null;
    if (selection != null && selectionArgs != null) {
        if (withAlias) {
            // Check for and
            Pattern pattern = Pattern.compile(" and | AND ");
            String[] data = pattern.split(selection);
            StringBuffer or_string = new StringBuffer();
            for (String token : data) {
                if (token.contains("OR") || token.contains("or")) {
                    or_string.append(token.trim());
                    or_string.append(" OR ");
                } else {
                    whr.append(base_alias + "." + token.trim());
                    whr.append(" AND ");
                }
            }
            if (whr.length() > 0)
                whr.delete(whr.length() - 5, whr.length());
            // Check for or
            if (or_string.length() > 0) {
                if (whr.length() > 0)
                    whr.append(" AND ");
                pattern = Pattern.compile(" or | OR ");
                data = pattern.split(or_string.toString());
                for (String token : data) {
                    if (!token.contains(base_alias)) {
                        if (token.contains("(")) {
                            whr.append("(");
                            token = token.replaceAll("\\(", "");
                            whr.append(base_alias + "." + token.trim());
                        } else if (token.contains(")")) {
                            token = token.replaceAll("\\)", "");
                            whr.append(base_alias + "." + token.trim());
                            whr.append(")");
                        } else {
                            whr.append(base_alias + "." + token.trim());
                        }
                    } else {
                        whr.append(token.trim());
                    }
                    whr.append(" OR ");
                }
                if (whr.length() > 0)
                    whr.delete(whr.length() - 4, whr.length());
            }
        } else {
            whr.append(selection);
        }
        where = whr.toString();
    }
    Cursor c = null;
    int uriMatch = matcher.match(uri);
    switch (uriMatch) {
    case SINGLE_ROW:
        // Return a single entry, by ID.
        String id = uri.getLastPathSegment();
        query.appendWhere(base_alias + "." + OColumn.ROW_ID + " = " + id);
    case COLLECTION:
        c = query.query(model.getReadableDatabase(), null, where, selectionArgs, null, null, sort);
        return c;
    default:
        throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
}