Mehedi Hassan Piash | Senior Software Engineer | Android | iOS | KMP | Ktor | Jetpack Compose | React-Native.

October 31, 2024

Room Database in Jetpack Compose: A Step-by-Step Guide for Android Development

October 31, 2024 Posted by Piash , , , , , No comments

 Room Database is part of Android’s Architecture Components and serves as an abstraction layer over SQLite. It simplifies data management by offering a type-safe way to interact with the database and enables compile-time checks of SQL statements.

Key Components of Room Database

1. Entity: Represents a table in your database.

2. DAO (Data Access Object): Contains methods for accessing the database.

3. Database Class: Acts as the main access point to the underlying SQLite database.

Step 1: Add Dependencies

To get started, include the Room dependencies in your libs.versions.toml file:

Include the Room dependencies in your app build.gradle. file:

Include the Room dependencies in your project build.gradle. file:

Step 2: Define an Entity

An Entity represents a table within the database. Define your entity as a data class, with each property corresponding to a column.

In this above code:

• @Entity marks this class as a Room entity.

  • @PrimaryKey denotes the primary key for this entity. Here, autoGenerate automatically assigns a unique ID for each User.

Step 3: Create a DAO

The DAO (Data Access Object) interface contains methods for accessing the database. Use SQL queries to define how data should be inserted, updated, retrieved, or deleted.

Each method is annotated with a specific Room operation (@Insert, @Update, @Delete, @Query) to specify the desired action.

Step 4: Create the Database Class

The Database class should be an abstract class extending RoomDatabase. Use the @Database annotation to specify the entities and database version.

if you have a nested data class inside Entity you have to add TypeConverter

Step 5: Build the Database

To build the database, use Room’s databaseBuilder method. This is typically done in your Application class or a dependency injection setup like Hilt.

Or, with Hilt:

Step 6: Perform Database in ViewModel

Step 7: Perform Database in Jetpack UI

Step 8: Here is the final result

Github: https://github.com/piashcse/Hilt-MVVM-Compose-Movie
Medium: https://piashcse.medium.com/room-database-in-jetpack-compose-a-step-by-step-guide-for-android-development-6c7ae419105a

0 comments:

Post a Comment