Java Code Examples for android.database.sqlite.SQLiteQueryBuilder#setTables()

The following examples show how to use android.database.sqlite.SQLiteQueryBuilder#setTables() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FailedActionParameterDbAdapter.java    From LibreTasks with Apache License 2.0 6 votes vote down vote up
/**
 * Return a Cursor that contains all FailedActionParameter records which matches the parameters.
 * 
 * @param failedActionID
 *          is id of failed action it belongs to, or null to fetch any
 * @param actionParameterName
 *          name of action parameter, or null to fetch any
 * @param failedActionParameterData
 *          is the data associated with this parameter, or null to fetch any
 * @return a Cursor that contains all FailedActionParameter records which matches the parameters.
 */
public Cursor fetchAll(Long failedActionID, String actionParameterName, 
    String failedActionParameterData) {

  SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
  qb.setTables(DATABASE_TABLE);
  qb.appendWhere("1=1");
  if (failedActionID != null) {
    qb.appendWhere(" AND " + KEY_FAILEDACTIONID + " = " + failedActionID);
  }
  if (actionParameterName != null) {
    qb.appendWhere(" AND " + KEY_ACTIONPARAMETERNAME + " = " + actionParameterName);
  }
  if (failedActionParameterData != null) {
    qb.appendWhere(" AND " + KEY_FAILEDACTIONPARAMETERDATA + " = ");
    qb.appendWhereEscapeString(failedActionParameterData);
  }
  // Not using additional selections, selectionArgs, groupBy, having, orderBy, set them to null.
  return qb.query(database, KEYS, null, null, null, null, null);
}
 
Example 2
Source File: BaseContentProvider.java    From droitatedDB with Apache License 2.0 6 votes vote down vote up
@Override
public Cursor query(final Uri uri, final String[] projection, final String selection, final String[] selectionArgs, final String sortOrder) {
	SQLiteDatabase db = dbCreator.getDatabaseConnection();
	SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
	builder.setTables(getTableName());
	switch (uriMatcher.match(uri)) {
		case MATCH_DIR:
			return wrap(builder.query(db, projection, selection, selectionArgs, null, null, sortOrder), uri);
		case MATCH_ITEM:
			int id = Integer.parseInt(uri.getLastPathSegment());
			builder.appendWhere(getIdName() + " = " + id);
			return wrap(builder.query(db, projection, selection, selectionArgs, null, null, sortOrder), uri);
		default:
			throw new UnsupportedOperationException("Unsupported query Uri " + uri);
	}
}
 
Example 3
Source File: ContactDBProvider.java    From VyAPI with MIT License 6 votes vote down vote up
@Override
public Cursor query(Uri uri, String[] projection, String selection,
                    String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(contactDBHandler.CONTACTS_TABLE);

    int uriType = uriMatcher.match(uri);

    switch (uriType) {
        case SINGLE_CONTACT:
            queryBuilder.appendWhere(contactDBHandler.COLUMN_FNAME + "="
                    + uri.getLastPathSegment());
            break;
        case ALL_CONTACTS:
            break;
        default:
            throw new IllegalArgumentException("Unknown URI");
    }

    Cursor cursor = queryBuilder.query(contactDBHandler.getReadableDatabase(),
            projection, selection, selectionArgs, null, null,
            sortOrder);
    cursor.setNotificationUri(getContext().getContentResolver(),
            uri);
    return cursor;
}
 
Example 4
Source File: MonsterHunterDatabaseHelper.java    From MonsterHunter4UDatabase with MIT License 5 votes vote down vote up
private SQLiteQueryBuilder builderItemToSkillTree() {
//		SELECT itst._id AS _id, itst.item_id, itst.skill_tree_id,
//		itst.point_value, i.name AS iname, s.name AS sname
//		FROM item_to_skill_tree AS itst
//		LEFT OUTER JOIN items AS i ON itst.item_id = i._id
//		LEFT OUTER JOIN skill_trees AS s ON itst.skill_tree_id = s._id;
//		LEFT OUTER JOIN armor AS a ON i._id = a._id 
//		LEFT OUTER JOIN decorations AS d ON i._id = d._id;

        String itst = "itst";
        String i = "i";
        String s = "s";

        HashMap<String, String> projectionMap = new HashMap<String, String>();

        projectionMap.put("_id", itst + "." + S.COLUMN_ITEM_TO_SKILL_TREE_ID + " AS " + "_id");
        projectionMap.put(S.COLUMN_ITEM_TO_SKILL_TREE_ITEM_ID, itst + "." + S.COLUMN_ITEM_TO_SKILL_TREE_ITEM_ID);
        projectionMap.put(S.COLUMN_ITEM_TO_SKILL_TREE_SKILL_TREE_ID, itst + "." + S.COLUMN_ITEM_TO_SKILL_TREE_SKILL_TREE_ID);
        projectionMap.put(S.COLUMN_ITEM_TO_SKILL_TREE_POINT_VALUE, itst + "." + S.COLUMN_ITEM_TO_SKILL_TREE_POINT_VALUE);

        projectionMap.put(i + S.COLUMN_ITEMS_NAME, i + "." + S.COLUMN_ITEMS_NAME + " AS " + i + S.COLUMN_ITEMS_NAME);
        projectionMap.put(S.COLUMN_ITEMS_ICON_NAME, i + "." + S.COLUMN_ITEMS_ICON_NAME);
        projectionMap.put(S.COLUMN_ITEMS_TYPE, i + "." + S.COLUMN_ITEMS_TYPE);
        projectionMap.put(S.COLUMN_ITEMS_SUB_TYPE, i + "." + S.COLUMN_ITEMS_SUB_TYPE);
        projectionMap.put(S.COLUMN_ITEMS_RARITY, i + "." + S.COLUMN_ITEMS_RARITY);
        projectionMap.put(s + S.COLUMN_SKILL_TREES_NAME, s + "." + S.COLUMN_SKILL_TREES_NAME + " AS " + s + S.COLUMN_SKILL_TREES_NAME);

        //Create new querybuilder
        SQLiteQueryBuilder QB = new SQLiteQueryBuilder();

        QB.setTables(S.TABLE_ITEM_TO_SKILL_TREE + " AS itst" + " LEFT OUTER JOIN " + S.TABLE_ITEMS + " AS i" + " ON " + "itst." +
                S.COLUMN_ITEM_TO_SKILL_TREE_ITEM_ID + " = " + "i." + S.COLUMN_ITEMS_ID + " LEFT OUTER JOIN " + S.TABLE_SKILL_TREES +
                " AS s " + " ON " + "itst." + S.COLUMN_ITEM_TO_SKILL_TREE_SKILL_TREE_ID + " = " + "s." + S.COLUMN_SKILL_TREES_ID +
                " LEFT OUTER JOIN " + S.TABLE_ARMOR + " AS a" + " ON " + "i." + S.COLUMN_ITEMS_ID + " = " + "a." + S.COLUMN_ARMOR_ID +
                " LEFT OUTER JOIN " + S.TABLE_DECORATIONS + " AS d" + " ON " + "i." + S.COLUMN_ITEMS_ID + " = " + "d." +
                S.COLUMN_DECORATIONS_ID);

        QB.setProjectionMap(projectionMap);
        return QB;
    }
 
Example 5
Source File: FormsProvider.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs,
                    String sortOrder) {
    init();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables(FORMS_TABLE_NAME);

    switch (sUriMatcher.match(uri)) {
        case FORMS:
            qb.setProjectionMap(sFormsProjectionMap);
            break;

        case FORM_ID:
            qb.setProjectionMap(sFormsProjectionMap);
            qb.appendWhere(FormsProviderAPI.FormsColumns._ID + "=" + uri.getPathSegments().get(1));
            break;

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

    // Get the database and run the query
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);

    // Tell the cursor what uri to watch, so it knows when its source data changes
    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}
 
Example 6
Source File: ServerDatabaseHandler.java    From an2linuxclient with GNU General Public License v3.0 5 votes vote down vote up
private List<WifiServer> getAllWifiServers(){
    List<WifiServer> allWifiServers = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();

    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    qb.setTables(TABLE_SERVERS +
            " JOIN " + TABLE_WIFI_SERVERS +
            " USING(" + COLUMN_ID + ")");

    Cursor c = qb.query(db,
            new String[]{COLUMN_ID,
                    COLUMN_IS_ENABLED,
                    COLUMN_CERTIFICATE_ID,
                    COLUMN_IP_OR_HOSTNAME,
                    COLUMN_PORT_NUMBER,
                    COLUMN_SSID_WHITELIST},
            null, null, null, null, null);

    if (c.moveToFirst()){
        do {
            WifiServer wifiServer = new WifiServer();
            wifiServer.setId(c.getLong(0));
            wifiServer.setIsEnabled(intToBool(c.getInt(1)));
            wifiServer.setCertificateId(c.getLong(2));
            wifiServer.setIpOrHostname(c.getString(3));
            wifiServer.setPortNumber(c.getInt(4));
            wifiServer.setSsidWhitelist(c.getString(5));
            allWifiServers.add(wifiServer);
        } while (c.moveToNext());
    }

    c.close();
    db.close();

    return allWifiServers;
}
 
Example 7
Source File: LauncherProvider.java    From LaunchEnr with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection,
                    String[] selectionArgs, String sortOrder) {
    createDbIfNotExists();

    SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables(args.table);

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
    result.setNotificationUri(getContext().getContentResolver(), uri);

    return result;
}
 
Example 8
Source File: MonsterHunterDatabaseHelper.java    From MonsterHunter4UDatabase with MIT License 5 votes vote down vote up
private SQLiteQueryBuilder builderArenaQuest() {
//		SELECT a._id AS _id, a.name AS aname, a.location_id, a.reward.,
//		a.num_participants, a.time_s, a.time_a, a.time_b,
//		l.name AS lname
//		FROM arena_quests AS a
//		LEFT OUTER JOIN locations AS l on a.location_id = l._id;

        String a = "a";
        String l = "l";

        HashMap<String, String> projectionMap = new HashMap<String, String>();

        projectionMap.put("_id", a + "." + S.COLUMN_ARENA_QUESTS_ID + " AS " + "_id");
        projectionMap.put(S.COLUMN_ARENA_QUESTS_NAME, a + "." + S.COLUMN_ARENA_QUESTS_NAME + " AS " + a + S.COLUMN_ARENA_QUESTS_NAME);
        projectionMap.put(S.COLUMN_ARENA_QUESTS_GOAL, a + "." + S.COLUMN_ARENA_QUESTS_GOAL);
        projectionMap.put(S.COLUMN_ARENA_QUESTS_LOCATION_ID, a + "." + S.COLUMN_ARENA_QUESTS_LOCATION_ID);
        projectionMap.put(S.COLUMN_ARENA_QUESTS_REWARD, a + "." + S.COLUMN_ARENA_QUESTS_REWARD);
        projectionMap.put(S.COLUMN_ARENA_QUESTS_NUM_PARTICIPANTS, a + "." + S.COLUMN_ARENA_QUESTS_NUM_PARTICIPANTS);
        projectionMap.put(S.COLUMN_ARENA_QUESTS_TIME_S, a + "." + S.COLUMN_ARENA_QUESTS_TIME_S);
        projectionMap.put(S.COLUMN_ARENA_QUESTS_TIME_A, a + "." + S.COLUMN_ARENA_QUESTS_TIME_A);
        projectionMap.put(S.COLUMN_ARENA_QUESTS_TIME_B, a + "." + S.COLUMN_ARENA_QUESTS_TIME_B);

        projectionMap.put(l + S.COLUMN_LOCATIONS_NAME, l + "." + S.COLUMN_LOCATIONS_NAME + " AS " + l + S.COLUMN_LOCATIONS_NAME);

        //Create new querybuilder
        SQLiteQueryBuilder QB = new SQLiteQueryBuilder();

        QB.setTables(S.TABLE_ARENA_QUESTS + " AS a" + " LEFT OUTER JOIN " + S.TABLE_LOCATIONS +
                " AS l " + " ON " + "a." + S.COLUMN_ARENA_QUESTS_LOCATION_ID + " = " + "l." + S.COLUMN_LOCATIONS_ID);

        QB.setProjectionMap(projectionMap);
        return QB;
    }
 
Example 9
Source File: EarthsProvider.java    From earth with GNU General Public License v3.0 5 votes vote down vote up
private Cursor queryEarthLatest(SQLiteDatabase db, @NonNull Uri uri, String[] projection) {
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    builder.setTables(EarthsContract.TABLE);

    Cursor cursor = builder.query(db, projection, null, null, null, null, EarthsContract.Columns.FETCHED_AT + " DESC", "1");

    //noinspection ConstantConditions
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    return cursor;
}
 
Example 10
Source File: LoaderThrottle.java    From codeexamples-android with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Handle incoming queries.
 */
@Override
public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String sortOrder) {

    // Constructs a new query builder and sets its table name
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables(MainTable.TABLE_NAME);

    switch (mUriMatcher.match(uri)) {
        case MAIN:
            // If the incoming URI is for main table.
            qb.setProjectionMap(mNotesProjectionMap);
            break;

        case MAIN_ID:
            // The incoming URI is for a single row.
            qb.setProjectionMap(mNotesProjectionMap);
            qb.appendWhere(MainTable._ID + "=?");
            selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
                    new String[] { uri.getLastPathSegment() });
            break;

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


    if (TextUtils.isEmpty(sortOrder)) {
        sortOrder = MainTable.DEFAULT_SORT_ORDER;
    }

    SQLiteDatabase db = mOpenHelper.getReadableDatabase();

    Cursor c = qb.query(db, projection, selection, selectionArgs,
            null /* no group */, null /* no filter */, sortOrder);

    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}
 
Example 11
Source File: RecipeContentProvider.java    From app-indexing with Apache License 2.0 5 votes vote down vote up
public Cursor getAllRecipes(String[] projection) {
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(RecipeTable.TABLE + ", " + RecipeNoteTable.TABLE);
    SQLiteDatabase db = database.getReadableDatabase();
    Cursor cursor = queryBuilder.query(db, projection, null, null, null, null, null);
    return cursor;
}
 
Example 12
Source File: SettingsProvider.java    From Study_Android_Demo with Apache License 2.0 5 votes vote down vote up
private void migrateLegacySettingsLocked(SettingsState settingsState,
        SQLiteDatabase database, String table) {
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(table);

    Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
            null, null, null, null, null);

    if (cursor == null) {
        return;
    }

    try {
        if (!cursor.moveToFirst()) {
            return;
        }

        final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
        final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);

        settingsState.setVersionLocked(database.getVersion());

        while (!cursor.isAfterLast()) {
            String name = cursor.getString(nameColumnIdx);
            String value = cursor.getString(valueColumnIdx);
            settingsState.insertSettingLocked(name, value, null, true,
                    SettingsState.SYSTEM_PACKAGE_NAME);
            cursor.moveToNext();
        }
    } finally {
        cursor.close();
    }
}
 
Example 13
Source File: WifiAuthDatabase.java    From WiFiAfterConnect with Apache License 2.0 5 votes vote down vote up
public Cursor getWifiTableCursor (final String[] projection, final String authHost) {
	SQLiteDatabase db = getDb();
	SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
	builder.setTables(WIFI_TABLE_NAME);
	Cursor c;
	if (authHost == null || authHost.isEmpty())
		c = builder.query(db, projection, null, null, null, null, null);
	else 
		c = builder.query(db, projection, COLUMN_HOSTNAME + " = ?", new String[] {authHost}, null, null, null); 

	// SQLite cursors are always not-null positioned before the first item 
	return c;	
}
 
Example 14
Source File: RecipeContentProvider.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
public Cursor getRecipe(Uri uri) {
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(RecipeTable.TABLE);
    String[] projection = { RecipeTable.ID, RecipeTable.TITLE,
            RecipeTable.DESCRIPTION, RecipeTable.PHOTO,
            RecipeTable.PREP_TIME};
    SQLiteDatabase db = database.getReadableDatabase();
    queryBuilder.appendWhere(RecipeTable.ID + "='"
            + uri.getLastPathSegment() + "'");
    Cursor cursor = queryBuilder.query(db, projection, null,
            null, null, null, null);
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    return cursor;
}
 
Example 15
Source File: RuleActionDbAdapter.java    From LibreTasks with Apache License 2.0 5 votes vote down vote up
/**
 * Return a Cursor that contains all RuleAction records which matches the parameters.
 * 
 * @param ruleID
 *          is id of the rule it belongs to, or null to fetch any.
 * @param actionID
 *          is id of its action type, or null to fetch any.
 * @return a Cursor that contains all RuleAction records which matches the parameters.
 */
public Cursor fetchAll(Long ruleID, Long actionID) {
  SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
  qb.setTables(DATABASE_TABLE);
  qb.appendWhere("1=1");
  if (ruleID != null) {
    qb.appendWhere(" AND " + KEY_RULEID + " = " + ruleID);
  }
  if (actionID != null) {
    qb.appendWhere(" AND " + KEY_ACTIONID + " = " + actionID);
  }

  // Not using additional selections, selectionArgs, groupBy, having, orderBy, set them to null.
  return qb.query(database, KEYS, null, null, null, null, null);
}
 
Example 16
Source File: RecipeContentProvider.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
public Cursor getIngredientsByRecipe(Uri uri) {
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(RecipeTable.TABLE + ", " + RecipeIngredientTable.TABLE);
    queryBuilder.appendWhere(RecipeTable.ID + "='" + uri.getLastPathSegment() + "' AND " + RecipeIngredientTable.RECIPE_ID + "=" + RecipeTable.ID + "");
    String[] projection = {RecipeIngredientTable.AMOUNT, RecipeIngredientTable.DESCRIPTION};
    SQLiteDatabase db = database.getReadableDatabase();
    Cursor cursor = queryBuilder.query(db, projection, null, null, null, null, null);
    cursor.setNotificationUri(getContext().getContentResolver(), uri);
    return cursor;
}
 
Example 17
Source File: RosterGroupManager.java    From yiim_v2 with GNU General Public License v2.0 5 votes vote down vote up
public Cursor query(SQLiteDatabase db, int type, Uri uri,
		String[] projection, String selection, String[] selectionArgs,
		String sortOrder) {

	SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
	qb.setTables(TABLE_NAME);

	if (type == UriType.ROSTER_GROUP.getCode()) {
		qb.setProjectionMap(mProjectionMap);
	} else if (type == UriType.ROSTER_GROUP_ID.getCode()) {
		qb.setProjectionMap(mProjectionMap);
		qb.appendWhere(RosterGroupColumns._ID + "="
				+ uri.getPathSegments().get(1));
	} else if (type == UriType.LIVE_FOLDER_ROSTER_GROUP.getCode()) {
		qb.setProjectionMap(mLiveFolderProjectionMap);
	} else {
		throw new IllegalArgumentException("Unknown URI " + uri);
	}

	// If no sort order is specified use the default
	String orderBy;
	if (TextUtils.isEmpty(sortOrder)) {
		orderBy = RosterGroupColumns.DEFAULT_SORT_ORDER;
	} else {
		orderBy = sortOrder;
	}

	// Get the database and run the query
	Cursor c = qb.query(db, projection, selection, selectionArgs, null,
			null, orderBy);

	return c;
}
 
Example 18
Source File: LabelProvider.java    From talkback with Apache License 2.0 4 votes vote down vote up
/**
 * 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.
 */
@Override
public Cursor query(
    Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
  if (uri == null) {
    LogUtils.w(TAG, 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 (uriMatcher.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.w(TAG, 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.w(TAG, UNKNOWN_URI_FORMAT_STRING, uri);
      return null;
  }

  initializeDatabaseIfNull();

  return queryBuilder.query(
      database, projection, selection, selectionArgs, groupBy, null /* having */, sortOrder);
}
 
Example 19
Source File: DevicesProvider.java    From device-database with Apache License 2.0 4 votes vote down vote up
@Override
public Cursor query(@NonNull Uri uri,
                    String[] projection,
                    String selection,
                    String[] selectionArgs,
                    String sortOrder) throws IllegalArgumentException {
    Cursor cursor;
    if (projection == null) {
        throw new IllegalArgumentException("Projection can't be null");
    }

    sortOrder = (sortOrder == null ? BaseColumns._ID : sortOrder);

    SQLiteDatabase database = helper.getReadableDatabase();

    final int code = URI_MATCHER.match(uri);
    switch (code) {
        case CODE_ALL_DEVICES:
        case CODE_ALL_MANUFACTURERS:
            cursor = database.query(URI_CODE_TABLE_MAP.get(code),
                    projection,
                    selection,
                    selectionArgs,
                    null,
                    null,
                    sortOrder);
            break;
        case CODE_DEVICE_ID:
        case CODE_MANUFACTURER_ID:
            if (selection == null) {
                selection = BaseColumns._ID
                        + " = "
                        + uri.getLastPathSegment();
            } else {
                throw new IllegalArgumentException("Selection must " +
                        "be null when specifying ID as part of uri.");
            }
            cursor = database.query(URI_CODE_TABLE_MAP.get(code),
                    projection,
                    selection,
                    selectionArgs,
                    null,
                    null,
                    sortOrder);
            break;
        case CODE_DEVICE_MANUFACTURER:
            SQLiteQueryBuilder builder = new SQLiteQueryBuilder();

            builder.setTables(String
                    .format("%s INNER JOIN %s ON (%s.%s=%s.%s)",
                    DevicesOpenHelper.Tables.DEVICE,
                    DevicesOpenHelper.Tables.MANUFACTURER,
                    DevicesOpenHelper.Tables.DEVICE,
                    DevicesContract.Device.MANUFACTURER_ID,
                    DevicesOpenHelper.Tables.MANUFACTURER,
                    DevicesContract.Manufacturer._ID));

            final Map<String, String> projectionMap = new HashMap<>();
            projectionMap.put(DevicesContract.DeviceManufacturer.MODEL,
                    DevicesContract.DeviceManufacturer.MODEL);

            projectionMap
                    .put(DevicesContract.DeviceManufacturer.SHORT_NAME,
                    DevicesContract.DeviceManufacturer.SHORT_NAME);

            projectionMap
                    .put(DevicesContract.DeviceManufacturer.DEVICE_ID,
                    String.format("%s.%s AS %s",
                            DevicesOpenHelper.Tables.DEVICE,
                            DevicesContract.Device._ID,
                            DevicesContract.DeviceManufacturer.DEVICE_ID));

            projectionMap.put(DevicesContract
                    .DeviceManufacturer.MANUFACTURER_ID,
                    String.format("%s.%s AS %s",
                            DevicesOpenHelper.Tables.MANUFACTURER,
                            DevicesContract.Manufacturer._ID,
                            DevicesContract
                                    .DeviceManufacturer.MANUFACTURER_ID));

            builder.setProjectionMap(projectionMap);

            cursor = builder.query(database,
                    projection,
                    selection,
                    selectionArgs,
                    null,
                    null,
                    sortOrder);

            break;
        default:
            throw new IllegalArgumentException("Invalid Uri: " + uri);
    }

    cursor.setNotificationUri(getContext().getContentResolver(), uri);
    return cursor;
}
 
Example 20
Source File: PlaceBadgeContentProvider.java    From android_coursera_1 with MIT License 3 votes vote down vote up
@Override
public Cursor query(Uri uri, String[] projection, String selection,
		String[] selectionArgs, String sortOrder) {
	
	SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

	qb.setTables(PlaceBadgesContract.BADGES_TABLE_NAME);

	Cursor c = qb.query(database, null, null, null, null, null, null);

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

	return c;

}