Search code examples
androidsqlsqlitesql-updateandroid-cursor

SQLite Database Update Needs Application to ReOpen to Actually Show New Values


public void updateRow(int form_no, String form_name, String question_name, String answer_1, String answer_2, String answer_3, int answer_1_count, int answer_2_count, int answer_3_count) {
    String sql = "UPDATE " + DATABASE_TABLE + " SET " + KEY_ANSWER_1_COUNT + " = " + answer_1_count + ", " +KEY_ANSWER_2_COUNT + " = " + answer_2_count + ", " + KEY_ANSWER_3_COUNT + " = " + answer_3_count + " " +
            "WHERE " + KEY_FORM_NO + "=" + form_no + " AND " + KEY_QUESTION_NAME + " = ?";


    Cursor c = db.rawQuery(sql, new String[]{question_name});
    c.close();
}

db is an object of Sqlite. I have used db.update() as well which isn't work either. Im trying to increase counter for key_answers by 1 when using this method, but it doesnt work. It only update once and I cant show it either. Only time I see the update actually placed is when I reopen the application and it doesnt accurate neither since it only updates once where I call update 3-4 more times.

Whats the problem here, how can I resolve this ? Thank you.

EDIT:

So after I saw "Der Golem"'s comment, I thought its better idea to go for db.update() method because on the docs says dont use db.execSql() use db.insert() db.update() db.delete() instead. For everyone struggle with the problem Im posting my working result.

String where = KEY_FORM_NO + "=" + form_no + " AND " + KEY_QUESTION_NAME + " = ?";
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_FORM_NO, form_no);
    newValues.put(KEY_FORM_NAME, form_name);
    newValues.put(KEY_QUESTION_NAME, question_name);
    newValues.put(KEY_ANSWER_1, answer_1);
    newValues.put(KEY_ANSWER_2, answer_2);
    newValues.put(KEY_ANSWER_3, answer_3);
    newValues.put(KEY_ANSWER_1_COUNT, answer_1_count);
    newValues.put(KEY_ANSWER_2_COUNT, answer_2_count);
    newValues.put(KEY_ANSWER_3_COUNT, answer_3_count);

    db.update(DATABASE_TABLE,newValues,where,new String[]{question_name});

Why did I only use question_name for whereArgs is because question_name is a string and can be used in whereArgs which wants string array, but form_no is an integer value. If Any suggestions for cleaning this code, that'd be appreciated.


Solution

  • To execute a command (INSERT, UPDATE, REPLACE, DELETE, CREATE TABLE, ...), you have to use execSQL().
    rawQuery() is only for queries (SELECT).

    Also, your command is a weird mixture of bound (?) and unbound parameters...

    My suggestion is to use something cleaner, like

    String sql = "UPDATE " + DATABASE_TABLE + " SET " + KEY_ANSWER_1_COUNT + " = ?, " +KEY_ANSWER_2_COUNT + " = ?, " + KEY_ANSWER_3_COUNT + " = ? WHERE " + KEY_FORM_NO + " = ? AND " + KEY_QUESTION_NAME + " = ?";
    Cursor c = db.execSQL(sql, new String[]{answer_1_count, answer_2_count, answer_3_count, form_no, question_name});