Android Development

Google's android guide Home Contact

Room Database Library for Android

Room provides an abstraction layer over SQLite, simplifying database access in Android applications.

Some of the key features include:

  • Abstraction Over SQLite: Room provides a higher-level abstraction over SQLite, reducing the amount of boilerplate code required to create and manage a database.
  • Type-Safe Queries: Room uses compile-time checks for SQL queries, catching errors early in the development process and reducing runtime errors related to database operations.
  • Integration with LiveData: Room integrates with Android's LiveData and RxJava, allowing you to observe changes in the database and automatically update the UI when data changes.
  • Easy Migration: Room simplifies database schema changes, allowing you to make updates without losing existing data.
  • Less Boilerplate Code: Room maps database objects to Java objects with minimal boilerplate code.
  • Annotation-Based: Room uses annotations to define the database schema, making it easy to define and maintain the data model.

Major Room Components (@Entity, @Database, @Dao)

Entity (table within database): An Entity is a data class annotated with @Entity. The fields (data members) in this class represent columns, and the class itself corresponds to a table. The class defines the data structure for the corresponding table, facilitates automatic table creation, and ensures type safety when working with the database.

When a class is annotated with @Entity, it tells Room to treat instances of that class as rows in a database table. Each field (property) in the annotated class corresponds to a column in the database table. For example:

@Entity(tableName = "employees")
data class EmployeesEntity(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,
    val name: String,
    val position: String,
    val salary: Double
)

Here, the chosen field types and names for the "employees" table correspond to:

  • id: Auto-incremented primary key of type Long.
  • name: String field to store the employee's name.
  • position: String field to store the employee's job title.
  • salary: Double field to store the employee's salary.

DAO: A DAO (Data Access Object) is an interface responsible for defining methods to access the database. Different queries can be performed using corresponding annotations such as @Insert (insert records), @Delete (delete records), @Update (update records), and @Query (various queries).

Define a DAO interface containing methods for performing database operations on the EmployeesEntity table. These methods include insert, update, delete, and query operations.

@Dao
interface EmployeesDao {
    @Insert
    suspend fun insertEmployee(employee: EmployeesEntity)

    @Update
    suspend fun updateEmployee(employee: EmployeesEntity)

    @Delete
    suspend fun deleteEmployee(employee: EmployeesEntity)

    @Query("SELECT * FROM employees")
    suspend fun getAllEmployees(): List
}

Database: A database is an abstract class where all database entries (entities) are stored. The @Database annotation defines a database class that serves as the main access point to the SQLite database. This class is responsible for creating, opening, and managing the database instance and providing access to the Data Access Objects (DAOs) that allow database operations.

Define a database class that extends RoomDatabase and annotate it with @Database. In the entities parameter, specify the entity class (in this case, EmployeesEntity), and set the version number.

@Database(entities = [EmployeesEntity::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun employeesDao(): EmployeesDao

    companion object {
        private var instance: AppDatabase? = null

        fun getInstance(context: Context): AppDatabase {
            return instance ?: synchronized(this) {
                instance ?: buildDatabase(context).also { instance = it }
            }
        }

        private fun buildDatabase(context: Context): AppDatabase {
            return Room.databaseBuilder(context, AppDatabase::class.java, "app-database")
                .build()
        }
    }
}
  • @Database: Specifies the entity class and database version.
  • employeesDao(): Provides access to the EmployeesDao interface.
  • companion object: Provides a singleton instance of the AppDatabase.

Summary Steps to Use Room Database

  • Add Dependencies: Add the Room dependencies to the app's build.gradle file.
  • Define Entity Class: Create entity classes representing the database tables. Annotate these classes with @Entity, and specify the table name and primary key.
  • Create Database: Create an abstract class that extends RoomDatabase and defines the database and its tables. Annotate this class with @Database and specify the list of entity classes.
  • Create Data Access Objects (DAOs): Create interfaces or abstract classes for DAOs and define methods for database operations, such as inserting, updating, deleting, and querying data. Annotate DAO methods with appropriate annotations (e.g., @Insert, @Delete, @Update, @Query).
  • Initialize Room Database: Obtain an instance of your Room database using a RoomDatabase.Builder and the build() method. Typically do this in an application class or in an activity's onCreate method.
    val database = AppDatabase.getInstance(applicationContext)
            
  • Perform Database Operations: Use the defined DAOs to perform database operations. Execute database operations on a background thread, and Room will automatically handle thread synchronization.