Example usage for android.database.sqlite SQLiteQueryBuilder setProjectionMap

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

Introduction

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

Prototype

public void setProjectionMap(Map<String, String> columnMap) 

Source Link

Document

Sets the projection map for the query.

Usage

From source file:com.appsimobile.appsii.module.home.provider.HomeContentProvider.java

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

    selection = fixWhereProjection(uri, selection);
    SqlArguments args = new SqlArguments(uri, selection, selectionArgs);

    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    String tables = createTablesFromTableQuery(args.table);

    qb.setTables(tables);//from  ww  w .ja  v a2 s .co  m

    Map<String, String> projectionMap = getProjectionMapForTable(args.table);

    if (projectionMap != null) {
        qb.setProjectionMap(projectionMap);
        qb.setStrict(true);
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    if (HomeContract.CELLS_TABLE_NAME.equals(args.table)) {
        sortOrder = fixSortOrder(sortOrder);
    }
    String where = args.where;
    if (HomeContract.HOTSPOT_PAGES_DETAILS_TABLE_NAME.equals(args.table)) {
        where = "_ht." + BaseColumns._ID + "=" + ContentUris.parseId(uri);
    }

    Cursor result = qb.query(db, projection, where, args.args, null, null, sortOrder);

    result.setNotificationUri(getContext().getContentResolver(), uri);

    return result;
}

From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java

private Cursor queryArtwork(@NonNull final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    ContentResolver contentResolver = getContext() != null ? getContext().getContentResolver() : null;
    if (contentResolver == null) {
        return null;
    }/*  www .ja v a  2s  . c  om*/
    final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables(MuzeiContract.Artwork.TABLE_NAME + " INNER JOIN " + MuzeiContract.Sources.TABLE_NAME + " ON "
            + MuzeiContract.Artwork.TABLE_NAME + "." + MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME
            + "=" + MuzeiContract.Sources.TABLE_NAME + "." + MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME);
    qb.setProjectionMap(allArtworkColumnProjectionMap);
    final SQLiteDatabase db = databaseHelper.getReadableDatabase();
    if (MuzeiProvider.uriMatcher.match(uri) == ARTWORK_ID) {
        // If the incoming URI is for a single source identified by its ID, appends "_ID = <artworkId>"
        // to the where clause, so that it selects that single piece of artwork
        qb.appendWhere(
                MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + "=" + uri.getLastPathSegment());
    }
    String orderBy;
    if (TextUtils.isEmpty(sortOrder))
        orderBy = MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED + " DESC, "
                + MuzeiContract.Artwork.DEFAULT_SORT_ORDER;
    else
        orderBy = sortOrder;
    final Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy, null);
    c.setNotificationUri(contentResolver, uri);
    return c;
}

From source file:org.kontalk.provider.UsersProvider.java

@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sortOrder) {/*  w  w  w  .  ja  va 2 s .  com*/
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    boolean offline = Boolean.parseBoolean(uri.getQueryParameter(Users.OFFLINE));

    int match = sUriMatcher.match(uri);
    if (match == USERS || match == USERS_JID) {
        // use the same table name as an alias
        String table = offline ? (TABLE_USERS_OFFLINE + " " + TABLE_USERS) : TABLE_USERS;
        qb.setTables(table);
        qb.setProjectionMap(usersProjectionMap);
    } else if (match == KEYS || match == KEYS_JID || match == KEYS_JID_FINGERPRINT) {
        qb.setTables(TABLE_KEYS);
        qb.setProjectionMap(keysProjectionMap);
    }

    switch (match) {
    case USERS:
        // nothing to do
        break;

    case USERS_JID: {
        // TODO append to selection
        String userId = uri.getPathSegments().get(1);
        selection = TABLE_USERS + "." + Users.JID + " = ?";
        selectionArgs = new String[] { userId };
        break;
    }

    case KEYS:
        // nothing to do
        break;

    case KEYS_JID:
    case KEYS_JID_FINGERPRINT:
        String userId = uri.getPathSegments().get(1);
        selection = DatabaseUtilsCompat.concatenateWhere(selection, Keys.JID + "=?");
        selectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs, new String[] { userId });
        // TODO support for fingerprint in Uri
        break;

    default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
    if ((match == USERS || match == USERS_JID) && c.getCount() == 0
            && (match != USERS_JID || !XMPPUtils.isDomainJID(uri.getPathSegments().get(1)))) {
        // empty result set and sync requested
        SyncAdapter.requestSync(getContext(), false);
    }
    if (Boolean.parseBoolean(uri.getQueryParameter(Users.EXTRA_INDEX)) && c.getCount() > 0) {
        UsersCursor uc = new UsersCursor(c);
        bundleFastScrollingIndexExtras(uc, uri, db, qb, selection, selectionArgs, sortOrder, null);
        c = uc;
    }

    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}

From source file:com.gelakinetic.mtgfam.helpers.CardDbAdapter.java

/**
 * Performs a database query./*from   w  ww .  j  a v  a2  s  .  co  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
 * @throws FamiliarDbException
 */
private Cursor query(String selection, String[] selectionArgs, String[] columns) throws FamiliarDbException {
    /*
     * 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(DATABASE_TABLE_CARDS);
    builder.setProjectionMap(mColumnMap);

    Cursor cursor = null;
    try {
        cursor = builder.query(mDb, columns, selection, selectionArgs, KEY_NAME, null, KEY_NAME);
    } catch (SQLiteException e) {
        throw new FamiliarDbException(e);
    } catch (IllegalStateException e) {
        throw new FamiliarDbException(e);
    }

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

    return cursor;
}

From source file:pl.selvin.android.syncframework.content.BaseContentProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    final int code = contentHelper.matchUri(uri);
    if (code != UriMatcher.NO_MATCH) {
        if (code == ContentHelper.uriSyncCode) {
            return null;
        }/*from  w  w  w .  j a  va  2 s . c  o  m*/
        SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
        final TableInfo tab = contentHelper.getTableFromCode(code & ContentHelper.uriCode);
        builder.setTables(tab.name);
        if (isItemCode(code)) {
            if (isItemRowIDCode(code)) {
                selection = "isDeleted=0 AND ROWID=" + uri.getPathSegments().get(2)
                        + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
            } else {
                selection = "isDeleted=0" + tab.getSelection()
                        + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : "");
                int i = 0;
                final String[] old = selectionArgs;
                final int len = (old == null) ? 0 : old.length;
                selectionArgs = new String[len + tab.primaryKey.length];
                for (; i < tab.primaryKey.length; i++) {
                    selectionArgs[i] = uri.getPathSegments().get(i + 1);
                }
                if (len > 0) {
                    for (; i < old.length; i++) {
                        selectionArgs[i] = old[i - tab.primaryKey.length];
                    }
                }
            }
        } else {
            selection = "isDeleted=0" + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
        }
        builder.setProjectionMap(tab.map);

        Cursor cursor = builder.query(getReadableDatabase(), projection, selection, selectionArgs, null, null,
                sortOrder);
        if (DEBUG) {
            Log.d("Query",
                    builder.buildQuery(projection, selection, selectionArgs, null, null, sortOrder, null));
        }
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }
    throw new IllegalArgumentException("Unknown Uri " + uri);
}

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. jav a 2  s .co 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);
    }
}