Search code examples
javaandroiddatabasesqliteandroid-sqlite

How to update multiple columns of a single row in SQLite?


I have a table with only one row for the moment and I want to update some column of that row. the insert method is executed correctly while, update returns an id = 0 and printing the username is always the previous one and is not updated.

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table "+TABLE_NAME1+" (ID INTEGER PRIMARY KEY AUTOINCREMENT, USERNAME TEXT, WON INT, DRAW INT, LOST INT, CELLSNUMBER INT,RESULT INT)");        
}
public boolean addUserInformation(String name, int w, int l, int d, boolean firstTime){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(USERNAME, name);
        values.put(WIN, w);
        values.put(LOST, l);
        values.put(DRAW, d);

        long id = 0;
        if(firstTime == true ) {
            id = db.insert(TABLE_NAME1, null, values);
        }
        if(firstTime == false){
            id=db.update(TABLE_NAME1, values, "USERNAME = ? and WON = ? and DRAW = ?  and LOST = ?",new String[] {
                    name,
                    String.valueOf(w),
                    String.valueOf(d),
                    String.valueOf(l)
            });
        }
        if(id == -1)
            return false;
        else
            return true;
    }

Solution

  • I guess you want to update the row with USERNAME = name with the values w, d, l.
    The 3d argument of the update() method is the WHERE clause and in it you should have only:

    USERNAME = ?
    

    so do it like this:

    id = db.update(TABLE_NAME1, values, "USERNAME = ?", new String[] {name});
    

    The values w, d, l need not be inside the WHERE clause. They are saved in the variable values and will update the row in the table.