I need to delete the items that are already done (IS_ACTIVE = 1) from a todo list database, but my code just clears the database. What is my mistake here? Database example
private val todoTable = "TODO_TABLE"
private val isActive = "IS_ACTIVE"
fun deleteDone(){
val db = this.writableDatabase
val sqlSelectQuery = "SELECT * FROM $todoTable"
val cursor = db.rawQuery(sqlSelectQuery, null)
if(cursor.moveToFirst()){
do {
val sqlDeleteQuery = "DELETE FROM $todoTable WHERE $isActive = ${cursor.getInt(2)} = 1"
db.execSQL(sqlDeleteQuery)
}while(cursor.moveToNext())
}
db.close()
}
There is no need to select the rows with IS_ACTIVE = 1
and then loop to delete them 1 by 1.
Use the method delete()
to delete them all:
fun deleteDone(){
val db = this.writableDatabase
db.delete(todoTable, isActive + " = 1", null)
db.close()
}
Here, the 2nd argument of delete()
is the WHERE
clause and the sql statement will be interpreted as:
DELETE FROM TODO_TABLE WHERE IS_ACTIVE = 1
Or simpler:
fun deleteDone(){
val db = this.writableDatabase
db.delete(todoTable, isActive, null)
db.close()
}
because:
WHERE IS_ACTIVE
is equivalent to:
WHERE IS_ACTIVE = 1