WHERE IN clause in Android sqlite?

fediva picture fediva · Jun 7, 2011 · Viewed 24.1k times · Source

I can't get WHERE IN clause to work on android SQLite database.

Is there any way to execute a statement like this in android? :

SELECT body FROM table1 WHERE title IN ('title1', 'title2', 'title3')

Answer

epool picture epool · Mar 27, 2015

You can use TextUtils.join(",", parameters) to take advantage of sqlite binding parameters, where parameters is a list with "?" placeholders and the result string is something like "?,?,..,?".

Here is a little example:

Set<Integer> positionsSet = membersListCursorAdapter.getCurrentCheckedPosition();
List<String> ids = new ArrayList<>();
List<String> parameters = new ArrayList<>();
for (Integer position : positionsSet) {
    ids.add(String.valueOf(membersListCursorAdapter.getItemId(position)));
    parameters.add("?");
}
getActivity().getContentResolver().delete(
    SharedUserTable.CONTENT_URI,
    SharedUserTable._ID + " in (" + TextUtils.join(",", parameters) + ")",
    ids.toArray(new String[ids.size()])
);