查询

时间:2016-05-25 10:34:25

标签: android database sqlite cursor

我有一个看起来像{1,2,3 ..}的String [](一串ID)。

我想在Android中构建一个查询以获取与ID匹配的所有条目。 这是我的代码:

Cursor idFoodCursor = getContext().getContentResolver().query(
            uriFood,
            null,
            CookingContract.FoodEntry.COLUMN_NAME + " LIKE ?",
            new String[]{selectionArgs},
            null
    );

    if (idFoodCursor.moveToFirst()) {

        List<String> ids = new ArrayList<String>();
        while (!idFoodCursor.isAfterLast()) {
            ids.add(idFoodCursor.getString(idFoodCursor.getColumnIndex(CookingContract.FoodEntry._ID)));
            idFoodCursor.moveToNext();
        }
        idFoodCursor.close();

        //Convert the ArrayList in String[]
        String[] idSelectionArg = new String[ids.size()];
        ids.toArray(idSelectionArg);

        return new CursorLoader(
                getContext(),
                uriFood,
                FOOD_COLUMNS,
                CookingContract.FoodEntry._ID + " = ?",
                idSelectionArg,
                sortOrder
        );

    }

最后一个查询不起作用,因为我应该添加“?”作为我在数组中的ID:

Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 3 because the index is out of range.  The statement has 1 parameters.

如何解决问题,考虑到我想要的内容? (表中所有ID的对应关系)

2 个答案:

答案 0 :(得分:0)

所有过度提及的代码都可以替换为:

 return new CursorLoader(
            getContext(),
            uriFood,
            FOOD_COLUMNS,
            "_id IN (SELECT _id FROM food WHERE name LIKE ?)",
            new String[] {selectionArgs},
            sortOrder

    );

这就是我想要的工作。

答案 1 :(得分:0)

public class Constants {
    public static final String JOB_STATUS_CANCELLED = "Cancelled";
    public static final String JOB_STATUS_COMPLETE = "Complete";
}

selection = JobListContract.JobEntry.COLUMN_NAME_JOB_STATUS + " NOT IN ( ? , ? ) ";

// The spaces matter!!!!

selectionArgs = new String[]{ Constants.JOB_STATUS_COMPLETE, Constants.JOB_STATUS_CANCELLED };


c = db != null ? db.query(
                    JobListContract.JobEntry.TABLE_NAME,  // The table to query
                    projection,                               // The columns to return
                    selection,                                // The columns for the WHERE clause
                    selectionArgs,                            // The values for the WHERE clause
                    null,                                     // don't group the rows
                    null,                                     // don't filter by row groups
                    JobListContract.JobEntry.COLUMN_NAME_ENTRY_ID + " desc" // The sort order
            ) : null;