1

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!

2 Answers 2

3

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[]

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Never would have figured this out by my own.. I had to add sb.append(")"); to get the closing ). Current (working) code : ` for (int i=0; i < inItems.length; i++){ if (i > 0) sb.append(", "); sb.append("'" + inItems[i] + "'"); } sb.append(")"); String selection = sb.toString();` -- PLEASE edit your solution to add the ), so I can mark it correct. Thanks!
no problem =) sorry I missed that line while copying the code
0

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); 

2 Comments

For unknown no of vars; I get errors, missing ; on line 7, inString cannot be resolved to a variable, Type of expression must be Array, but resolved to String..
then just put ; after line like inString=inString+", ";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.