Search code examples
javaandroidsqliteandroid-sqlite

How do I update a specific row in a specific column in SQlite in Java?


So I have a pretty simple question I believe but can't seem to find any answers.

I am trying to update a single row of a single column in SQlite but using what I have right now, I seem to update the column for every row:

public void updateCompletedSessions(int i, User u) {
        ContentValues cv = new ContentValues();
        cv.put(ScheduleDbHelper.COLUMN_COMPLETION, i);

        SQLiteDatabase database = this.getWritableDatabase();

        database.update(TABLE_NAME, cv, "Username="+"Username", null);
    }

I have a User as argument to be able o check the name of that user so the Username column all have unique values of course, but where do I do the check? I'm thinking it has something to do with the last argument to the update() method?


Solution

  • Your condition:

    "Username="+"Username"
    

    is equivalent to:

    "Username=Username"
    

    which is always TRUE and this is why you update all the rows of the table.
    Your method's updateCompletedSessions() 2nd argument is u which is an object of type User and I assume there is a method defined for the class User like getName() or something similar.
    If this is the case then use it like this:

    database.update(TABLE_NAME, cv, "Username=?", new String[] {u.getName()});
    

    Always use placeholders ? and pass their values in the 4th argumement of update() instead of concatenating the arguments.