Search code examples
javaandroidsqliteandroid-sqlite

Update single value in SQL table in Android


I am trying to update a value in a SQL .db file that only has 1 row in 1 table. I just want to change the CUSTOMER_ISACTIVE column though.

    public static final String CUSTOMER_TABLE = "CUSTOMER_TABLE";
    public static final String COLUMN_CUSTOMER_EMAIL = "CUSTOMER_EMAIL";
    public static final String COLUMN_CUSTOMER_PASSWORD = "CUSTOMER_PASSWORD";
    public static final String COLUMN_CUSTOMRER_ISMEMBER = "CUSTOMRER_ISMEMBER";
    public static final String COLUMN_CUSTOMER_ISACTIVE = "CUSTOMER_ISACTIVE";
    public static final String COLUMN_CUSTOMER_PAYMENTERROR = "CUSTOMER_PAYMENTERROR";
    public static final String COLUMN_CUSTOMER_AUTOCARDTOKEN = "CUSTOMER_CARDTOKEN";

public void upDateActiveStatus(boolean isActive){
        SQLiteDatabase db = this.getWritableDatabase();
        String SS = "UPDATE " + CUSTOMER_TABLE + " SET " + COLUMN_CUSTOMER_ISACTIVE  + "=" + isActive + " WHERE " + "ID = 1";
        db.execSQL(SS);

But this is not working. Because when I pull the value of isActive later (I know this part works) It is unchanged. Any ideas?

This was my error : java.lang.RuntimeException: android.database.sqlite.SQLiteException: no such column: true (code 1 SQLITE_ERROR): , while compiling: UPDATE CUSTOMER_TABLE SET CUSTOMER_ISACTIVE = true


Solution

  • The recommended way to update the table is by using the method update() with ContentValues.
    The method update() also returns the number of affected rows which you can check.
    So do it like this:

    public int upDateActiveStatus(boolean isActive){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_CUSTOMER_ISACTIVE, isActive ? 1 : 0);
        int rows = db.update(CUSTOMER_TABLE, cv, "ID = ?", new String[] {"1"});
        db.close();
        return rows;
    }
    

    You can call the method like this:

    int rows = upDateActiveStatus(true);
    

    and then check the value of the variable rows to check the number of the updated rows.