Skip to main content

Command Palette

Search for a command to run...

Unleashing the power of Room Database with SQLite Mastery

Updated
5 min read
Unleashing the power of Room Database with SQLite Mastery

INTRODUCTION


In modern Android app development, managing local data efficiently is critical for building any responsive and robust applications. The Room Database, a key component of Android Jetpack, provides a streamlined abstraction layer over SQLite, enabling developers to interact with a database using less boilerplate code.

This blog explores the crud essentials of Room Database, breaking down its core components and design principles. We'll delve into the role of entities as the building blocks of your database schema and their intricate mapping to SQLite tables. Furthermore, we'll discuss the significance of abstract classes, which serve as the cornerstone of Room's DAO (Data Access Object) implementation, allowing developers to define database operations with precision.

UNDERSTANDING CRUD OPERATIONS


RoomDatabase is a part of the Android Architecture Components and provides an abstraction layer over SQLite. It simplifies database work and allows for more robust database access while harnessing the full power of SQLite.

CRUD is an acronym that stands for Create, Read, Update, and Delete. These are the four fundamental operations performed on data in any database management system, including in Android development using SQLite and RoomDatabase.

Let’s break down each operation:

  1. Create: This operation involves adding new data to the database. In the context of an app, it could be something like adding a new record (e.g., a new ‘wish’ in a wish-list app). In SQL terms, this is usually done using the INSERT statement.

  2. Read: This operation is used to retrieve data from the database. It can be a query for a specific item or a request for all records that meet certain criteria. In SQL, the SELECT statement is used for this purpose.

  3. Update: This operation involves modifying existing data in the database. It is used when the information in a database needs to be changed or updated. In SQL, this is done using the UPDATE statement.

  4. Delete: This operation removes data from the database. When an item is no longer needed or relevant, it can be deleted, which removes its corresponding row from the database table. In SQL, this is done using the DELETE statement.

SQLite with Room: Entity and DAO

In Android development, particularly when using the Room Persistence Library, two key components come into play when interfacing with SQLite databases: Entity classes and Data Access Objects (DAOs).

Here’s a detailed look at each:

  1. Entity Class (@Entity):

    • Purpose: An Entity class in Room represents a table within the SQLite database. Each instance of an entity corresponds to a row in the table.

    • Structure:

      • Primary Key: Each entity must define at least one primary key. This is done using the @PrimaryKey annotation. For instance, @PrimaryKey(autoGenerate = true) can be used if you want the database to auto-generate the key.

      • Columns: The fields in the entity represent the columns of the table. You can customize the column name using the @ColumnInfo(name = "custom_name") annotation. If not specified, the column name will be the same as the field name.

    • Example: In this example, Wish is an entity with a table name wish_table, containing two columns: id and wish_desc.

  2. Data Access Object (DAO):

    • Purpose: DAOs are interfaces or abstract classes where you define methods to access your database. In other words, DAOs are the main component for defining the logic of your database operations.

    • Methods: Within a DAO, you define methods to perform your database operations (CRUD operations). Room translates these methods into SQLite queries.

      • Insert: Annotated with @Insert, used for adding records to the database.

      • Query: Annotated with @Query, used for reading data. You can write SQLite queries inside the annotation.

      • Update: Annotated with @Update, used to modify existing records.

      • Delete: Annotated with @Delete, used to remove records.

    • Example: This DAO defines methods for adding, retrieving, updating, and deleting wishes in the wish_table.

        @Dao
        interface WishDao {
            @Insert
            fun addWish(wish: Wish)
      
            @Query("SELECT * FROM wish_table")
            fun getAllWishes(): List<Wish>
      
            @Update
            fun updateWish(wish: Wish)
      
            @Delete
            fun deleteWish(wish: Wish)
        }
      

Setting up RoomDatabase

@Database(entities = [Wish::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun wishDao(): WishDao
}

ABSTRACT CLASSES IN KOTLIN


In Kotlin, an abstract class is a type of class that cannot be instantiated directly, meaning you cannot create an object of an abstract class.

Instead, it is meant to be a base class that other classes extend from. The key characteristics of an abstract class in Kotlin are:

  1. Abstract Methods: An abstract class can have abstract methods. These methods are declared without an implementation. The implementation of these methods must be provided by the subclasses that inherit the abstract class. This is useful for defining a common template for a group of subclasses.

  2. Non-Abstract Methods: Besides abstract methods, an abstract class can also have regular methods with implementations. This allows you to define shared behavior that subclasses can inherit or override.

  3. Instantiation: As mentioned, abstract classes cannot be instantiated on their own. They are designed to be subclassed, and their functionality is realized in their subclasses.

  4. Constructor: Like any other class, abstract classes can have constructors. These constructors are called when a subclass is instantiated.

    In the context of using Room with Kotlin for Android development, the abstract class plays a crucial role, particularly when defining DAOs (Data Access Objects).

    Here’s how:

    • DAO as an Abstract Class: When you define a DAO in Room, you typically declare it as an abstract class. This is because the DAO is not meant to be instantiated directly. Instead, Room takes care of creating an implementation for you.

    • Defining Database Operations: In your DAO, you define abstract methods for each database operation you want to perform (like adding, fetching, updating, or deleting data). Room generates the necessary code to perform these operations with SQLite.

    • Example:

        @Dao
        abstract class WishDao {
            @Insert
            abstract fun addWish(wish: Wish)
      
            @Query("SELECT * FROM wish_table")
            abstract fun getAllWishes(): List<Wish>
      
            // Other CRUD operations...
        }
      

CONCLUSION


This article provides an overview of the core of CRUD operations in RoomDatabase, the implementation of Entity and DAO, and the use of Kotlin’s abstract classes. These concepts are crucial for developing efficient, maintainable, and high-quality Android applications, setting a solid foundation for future development endeavors.