Search code examples
javaandroidsqliteandroid-sqlite

How update row in table with array


I am having trouble dealing with the following:

for(int i = 1; i <= 100; i++) {  
    values.put("id", i);
    DB.update("book", values, "_id between 1 and 100", null);
}

I am very sorry this is my code :

for(int i=0;i<strArray.length;i++){
values.put("id", strArray[i]);
DB.update("book", values, "_id between 1 and 100", null);
}

I want to update the column id with strArray in other words I want add all strArray in column id where _id between 1 to 100 again so sorry

the result in table :

enter image description here

Can someone help me.


Solution

  • Your code updates in every iteration of the for loop all the rows of the table with _ids 1 up to 100.
    Each iteration uses the value of the variable i to update the column id of all these rows and what you see is the final result with the final value of i which is 100.
    If what you want is to update the column id with the value x in the row with _id = x then change to this:

    for(int i = 1; i <= 100; i++) {  
        values.put("id", i);
        DB.update("book", values, "_id = " + i, null);
    }
    

    or better with a placeholder:

    for(int i = 1; i <= 100; i++) {  
        values.put("id", i);
        DB.update("book", values, "_id = ?", new String[] {String.valueOf(i)});
    }
    

    or with a single statement:

    DB.execSQL("UPDATE book SET id = _id WHERE _id BETWEEN 1 AND 100");