Sqlite record not inserted

Viewed 28

I have the following code but if I add one more column it doesn't insert the record. The column I try to insert is date. If I remove this column everything works but if I add the column date then the exception Record not Added appears.

public void insert(){
    try {
        String name = ed1.getText().toString();
        String course = ed2.getText().toString();
        String fee  = ed3.getText().toString();
        //String date = (String) selectedDateTV.getText();
        String date = "test date";
        SQLiteDatabase db = openOrCreateDatabase("SliteDB", Context.MODE_PRIVATE, null);

        db.execSQL("CREATE TABLE IF NOT EXISTS records (id INTEGER not null, name VARCHAR not null, course varchar,  fee VARCHAR, date varchar)");
        String sql = "insert into records(name, course, fee, date) values(?, ?, ?, ?)";
       
        SQLiteStatement  statement = db.compileStatement(sql);

        statement.bindString(1,name);
        statement.bindString(2,course);
        statement.bindString(3,fee);
        statement.bindString(4,date);

        statement.execute();
        Toast.makeText( this, "Record Added", Toast.LENGTH_SHORT).show();

        ed1.setText("");
        ed2.setText("");
        ed3.setText("");
        //selectedDateTV.setText("");
        ed1.requestFocus();


    }
    catch (Exception ex)
    {
        Toast.makeText( this, "Record Not Added", Toast.LENGTH_SHORT).show();
    }
}
1 Answers

Try migrating, it will work. Sample code is below

private fun upgradeVersion2(db: SQLiteDatabase) {
    db.execSQL("ALTER TABLE $DATABASE_TABLE ADD COLUMN $KEY_VALUE INTEGER DEFAULT 0;")

    val cursor = db.query(DATABASE_TABLE, RESULT_COLUMNS, null, null, null, null, null, null)
    if (cursor != null) {
        var hasItem = cursor.moveToFirst()
        while (hasItem) {
            val id = cursor.getInt(cursor.getColumnIndex(KEY_ID))
            val nameStr = cursor.getString(cursor.getColumnIndex(KEY_NAME))
            val values = ContentValues()
            values.put(KEY_VALUE, nameStr.length)
            db.update(DATABASE_TABLE, values, "$KEY_ID=?", arrayOf(id.toString()))
            hasItem = cursor.moveToNext()
        }
        cursor.close()
    }
}
Related