Why Choose Room Database?

Abhishek Pathak
5 min readMar 15, 2024
  • Compile-time Verification: Room Database employs SQL queries such as @Query, @Entity, @Insert, @Update, etc., which undergo compile-time verification. This proactive approach prevents runtime crashes, enhancing app stability.
  • Boilerplate Code Reduction: Leveraging an annotation-based structure, Room Database abstracts away much of the redundant code, streamlining development processes. Developers can focus on utilizing annotations like @Insert, @Delete, @Update, etc., without delving into unnecessary implementation details.
  • Integration with Android Jetpack: As an integral part of Android Jetpack, Room Database seamlessly integrates with architectural components like LiveData, ViewModel, RXJava, Coroutines, facilitating efficient app development.

Understanding Room Database

Room Database offers a higher-level abstraction compared to SQLite, easing the burden on developers. This architecture comprises distinct components:

  • Entity: Represented by a data class annotated with @Entity, it encapsulates table details, including table name and columns.
  • Dao (Data Access Object): Annotated with @Dao, this interface consolidates CRUD (Create, Read, Update, Delete) operations, providing a streamlined approach to database interactions.
  • Database: An abstract class serving as the backbone of Room Database, it encapsulates database details and provides a database builder instance accessible throughout the application. Passing the application context ensures global accessibility, transcending activity scope.

Key Annotations in Room Database

Annotations play a pivotal role in Room Database, guiding compiler and runtime behavior. Some essential annotations include:

  • @Entity: Designates a class as an entity, representing a table within the database.
  • @PrimaryKey: Marks a field as the primary key of the corresponding table.
  • @ColumnInfo: Specifies column details such as name, data type, and constraints within a table.
  • @Dao: Identifies an interface as a Data Access Object, defining methods for database operations.
  • @Database: Annotates a class as a Room database, facilitating database creation and management.
  • @TypeConverter: Defines converters for non-native data types, aiding in seamless data conversion.
  • @Relation: Establishes relationships between entities, facilitating querying of related data.
  • @Query: Defines custom SQL queries for specific database operations.
  • @ForeignKey: Specifies foreign key relationships between entities, ensuring database integrity.
  • @Embedded: Includes fields from another class within an entity, simplifying complex data storage scenarios.

Room is an abstraction layer on top of SQLite that makes it easier and best way in android to persist data.

Implementation Steps for CRUD Operations

Let’s outline the steps to create a CRUD app using Room Database:

Photo by Matt Duncan on Unsplash

Set Up Dependencies: Define dependencies for Room Database in the project.

def roomVersion = "2.4.2"
implementation("androidx.room:room-runtime:$roomVersion")
kapt("androidx.room:room-compiler:$roomVersion")

Create Entity: Define entity classes with necessary annotations.

// Note.kt

import androidx.room.Entity
import androidx.room.PrimaryKey

// Annotates the class as an Entity in the Room Database, representing a table named "Note".
@Entity(tableName = "Note")
data class Note(

// Marks this field as the primary key of the "Note" table, with auto-generation enabled.
@PrimaryKey(autoGenerate = true)
val id: Int = 0, // Primary key representing the unique identifier of the note.

val title: String, // Represents the title of the note.
val content: String // Represents the content of the note.
)

Create Dao: Implement Data Access Objects with CRUD operation methods.

// NoteDao.kt

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update

// Annotates the interface as a Data Access Object (DAO) for Note entities.
@Dao
interface NoteDao {

// Inserts a new note into the "Note" table.
@Insert
fun insert(note: Note)

// Deletes a note from the "Note" table.
@Delete
fun delete(note: Note)

// Retrieves all notes from the "Note" table.
@Query("SELECT * FROM Note")
fun getAllNotes(): List<Note>

// Updates an existing note in the "Note" table.
@Update
fun update(note: Note)
}

Create Database: Develop an abstract class representing the Room database and its builder instance.

// AppDatabase.kt

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

// Annotates the class as a Room Database, specifying the list of entities and database version.
@Database(entities = [Note::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {

// Abstract method to provide access to the NoteDao interface.
abstract fun noteDao(): NoteDao

companion object {
@Volatile
private var INSTANCE: AppDatabase? = null

// Provides a singleton instance of the AppDatabase class.
fun getInstance(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"notes_database"
).build()
INSTANCE = instance
instance
}
}
}
}

Implement App Logic: Utilize the Room Database throughout the app for data management.

// MainActivity.kt

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity

// Represents the main activity of the application.
class MainActivity : AppCompatActivity() {

// Called when the activity is first created.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Retrieve an instance of the AppDatabase and NoteDao.
val db = AppDatabase.getInstance(this)
val noteDao = db.noteDao()

// Create a sample note and insert it into the database.
val note = Note(title = "Sample Note", content = "This is a sample note content.")
noteDao.insert(note)

// Retrieve all notes from the database and log them.
val allNotes = noteDao.getAllNotes()
Log.d("MainActivity", "All Notes: $allNotes")
}
}

Room Database Series:

Type Converters: Exploring how to use Type Converters in Room Database to handle custom data types.

Migration in Room Database: A detailed guide on managing database schema changes and version migrations in Room Database.

Storing Images in Room Database: Techniques for storing and retrieving images in Room Database efficiently.

Working with Multiple Tables in Room Database: Strategies for designing and managing multiple tables and relationships in Room Database.

Explore Room Database masterpiece on my GitHub

Conclusion

Room Database emerges as a superior alternative to SQLite, streamlining development processes and enhancing app robustness. By leveraging its annotation-based approach and integration with Android Jetpack, developers can create efficient and scalable applications.

Stay tuned for more insightful articles on Android components, Android Jetpack, and Jetpack Compose.

If you found this article helpful, don’t forget to clap! Your feedback is invaluable for improvement.
let’s connect on
Linkedin , GitHub

--

--