Reputation: 770
I have the variable string (user gets to set it via a ListView with tickboxes, so string can contain any number of fruits)
private static final String kernset = "Banana, Peach"
I have the following SQLite Query
Cursor cursor = db.query (TABLE_NAME, new String[] {
WOORD },
"kern IN (\"Banana\", \"Apple\")", null, null, null, null, null);
I want to replace the (\"Banana\", \"Apple\") part of the query with the variable.
How should I do that?
Thanks!
Upvotes: 1
Views: 2289
Reputation: 9753
If you want to place a variable into your selection
parameter, you can split your string using split method, and then form your selection like
StringBuilder sb = new StringBuilder();
sb.append("kern IN (");
String[] inItems = kernset.split("\\,\\s+");
for (int i=0; i < inItems.length; i++){
if (i > 0)
sb.append(", ");
sb.append("'" + inItems[i] + "'");
}
sb.append(")");
String selection = sb.toString();
however if you wish to use ?
in selection
and replace it with selectionArgs[]
it seems to be imposible since values passed in selectionArgs
are surrounded with ' '
. You can however form selection with ?
instead of actual values (like kern IN (?, ?, ?)
)and then pass inItems
via selectionArgs[]
Upvotes: 3
Reputation:
by just using concatenation like
Cursor cursor = db.query (TABLE_NAME, new String[] {
WOORD },
"kern IN (\""+var1+"\", \""+var2+"\")", null, null, null, null, null);
for unknow no of vars
inString="";
for(int i=0;i<fruits.length();i++)
{
inString=inString+"\""+fruits[i]+"\"";
if(i<(fruits.length()-1))
{
inString=inString+", "
}
}
Cursor cursor = db.query (TABLE_NAME, new String[] { WOORD },
"kern IN ("+inString+")", null, null, null, null, null);
Upvotes: 0