Home > OS >  android sqlite unlimited bind arguments
android sqlite unlimited bind arguments

Time:09-26

I use this code to update my records in java:

    ArrayList<String> goalsNameList = new ArrayList<>();
    for (Goal goal : goalsList) {
        goalsNameList.add(goal.getName());
    }
    String[] goals = goalsNameList.toArray(new String[0]);
    ContentValues cv = new ContentValues();
    cv.put(GoalEntry.COLUMN_GOAL_PARENT, parent.getName());
    sQLiteDatabase.update(GoalEntry.TABLE_NAME, cv, GoalEntry.COLUMN_GOAL_NAME   " IN (?, ?)", goals);

and I get this error:

java.lang.IllegalArgumentException: Too many bind arguments.  6 arguments were provided but the statement needs 3 arguments.

I've also tried instead of inserting goals as a String array of multiple arguments using a one-cell String array that holds all of the arguments concatenated with commas between them as if it's a normal SQL statement, it didn't leave an error message, but also didn't work (the cells weren't updated).

how can I make the valid number of arguments (bind arguments) unlimited? I don't know the number of arguments I get in the array, it's not limited to any number.

CodePudding user response:

Obviously, I can make a for loop, that adds "?, " for every goal in the array, and that code is working:

    ArrayList<String> goalsNameList = new ArrayList<>();
    for (Goal goal : goalsList) {
        goalsNameList.add(goal.getName());
    }
    String[] goals = goalsNameList.toArray(new String[0]);
    ContentValues cv = new ContentValues();
    cv.put(GoalEntry.COLUMN_GOAL_PARENT, parent.getName());
    StringBuilder inCluse = new StringBuilder(" IN (?");
    for(int i = 0; i < goals.length - 1; i   ){
        inCluse.append(", ?");
    }
    inCluse.append(")");
    sQLiteDatabase.update(GoalEntry.TABLE_NAME, cv, GoalEntry.COLUMN_GOAL_NAME   inCluse.toString(), goals);

this code is not complicated, but I thought there would be a 'cleaner' way to do that... is there?

  • Related