Sling Academy
Home/Kotlin/Deleting Records from SQLite Tables in Kotlin

Deleting Records from SQLite Tables in Kotlin

Last updated: November 30, 2024

In this article, we will explore how to delete records from SQLite tables using Kotlin, a versatile and widely-used programming language for Android development. Deleting records is a common database operation, and understanding how to execute it correctly is crucial for maintaining data integrity and ensuring application performance.

Setting Up SQLite Database in Kotlin

Before we can proceed with deleting records, we need to set up our SQLite database. We'll start by creating a database helper class that extends SQLiteOpenHelper. This class will help us manage database creation and version management.


import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper

class MyDatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
    companion object {
        const val DATABASE_NAME = "MyDatabase.db"
        const val DATABASE_VERSION = 1
    }

    override fun onCreate(db: SQLiteDatabase?) {
        db?.execSQL("CREATE TABLE MyTable (id INTEGER PRIMARY KEY, name TEXT)")
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        // Handle schema update logic here
        db?.execSQL("DROP TABLE IF EXISTS MyTable")
        onCreate(db)
    }
}

In this class, we create a simple table named MyTable with two columns: id and name. Now that our database and table are ready, we can proceed to delete records.

Deleting Records from SQLite Table

To delete records from a table, we can use the SQLiteDatabase's delete() method. This method allows us to specify which rows to delete using a condition provided by the whereClause parameter.


fun deleteRecordById(databaseHelper: MyDatabaseHelper, id: Long) {
    val db = databaseHelper.writableDatabase
    val selection = "id = ?"
    val selectionArgs = arrayOf(id.toString())

    val deletedRows = db.delete("MyTable", selection, selectionArgs)
    if (deletedRows > 0) {
        println("Record deleted successfully")
    } else {
        println("No record found with the provided id")
    }
}

In this snippet, the deleteRecordById function accepts an instance of MyDatabaseHelper and the id of the record that you want to delete. It sets up a selection criteria using the id to target the specific row and then calls the delete() method. The number of rows deleted is returned by the method, which helps us confirm whether a record was successfully deleted or not.

Deleting All Records

If you wish to delete all records from a table, you can pass null for both whereClause and selectionArgs when calling the delete() method.


fun deleteAllRecords(databaseHelper: MyDatabaseHelper) {
    val db = databaseHelper.writableDatabase
    db.delete("MyTable", null, null)
    println("All records have been deleted")
}

This function will remove all entries from MyTable, effectively clearing the table. However, be cautious when using this operation, as it is irreversible.

Conclusion

In this guide, we've covered the basics of setting up an SQLite database in Kotlin and methods to delete specific or all records from a table. Deleting data is a fundamental operation, and handling it diligently helps in maintaining data consistency and system reliability. Make sure to handle potential exceptions and provide necessary confirmation prompts in real applications to prevent accidental deletions.

Next Article: Working with SQLite Transactions in Kotlin

Previous Article: How to Update Records in SQLite Using Kotlin

Series: Kotlin - Interacting with Databases

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin