Kotlin has rapidly become a popular language for Android development. One of its powerful features is the integration with Room, a part of Android Jetpack that offers an abstraction layer over SQLite to smooth out the boilerplate code and streamline interactions with databases. In this article, we'll guide you through the steps required to set up Room in an Android project using Kotlin.
Step 1: Add Room to Your Project
Begin by adding Room to your project dependencies. Open the build.gradle file for your app module and include the following Room components:
dependencies {
def room_version = "2.4.3"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version" // Annotation processor
// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"
}Step 2: Enable Kotlin Kapt
To use Room with Kotlin, you need to enable Kotlin KAPT (Kotlin Annotation Processing Tool). This involves applying the kotlin-kapt plugin in your build.gradle:
apply plugin: 'kotlin-kapt'Step 3: Define Your Entity
In Room, an entity represents a table in your database. Create a data class and annotate it with @Entity to define a table:
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "users")
data class User(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val name: String,
val age: Int
)Step 4: Create a Data Access Object (DAO)
DAOs are responsible for defining the methods that access the database. Annotate your interface with @Dao, and use SQL queries to define data operations:
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
interface UserDao {
@Insert
suspend fun insert(user: User)
@Query("SELECT * FROM users")
suspend fun getAllUsers(): List<User>
}Step 5: Create the Room Database
Next, create an abstract class that extends RoomDatabase and includes methods to get your DAOs:
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [User::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}Step 6: Instantiate the Database
You'll need to build the database instance to use Room in your app. It is recommended to use a singleton pattern to avoid having multiple instances:
import android.content.Context
import androidx.room.Room
object DatabaseBuilder {
private var INSTANCE: AppDatabase? = null
fun getInstance(context: Context): AppDatabase {
if (INSTANCE == null) {
synchronized(AppDatabase::class) {
INSTANCE = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"app_database"
).build()
}
}
return INSTANCE!!
}
}Step 7: Using Room in Your Application
Once you have the setup done, interact with your Room database using the DAO objects. For instance, you could insert and retrieve user records as follows:
val db = DatabaseBuilder.getInstance(this)
val userDao = db.userDao()
GlobalScope.launch(Dispatchers.IO) {
val newUser = User(name = "John Doe", age = 30)
userDao.insert(newUser)
val users = userDao.getAllUsers()
users.forEach {
Log.d("User: ", "Id: ${it.id}, Name: ${it.name}, Age: ${it.age}")
}
}Note: While using coroutines, make sure operations are executed off the main thread. Here, we used Dispatchers.IO for making disk I/O safe.
In conclusion, integrating Room into your Android project using Kotlin enhances your ability to maintain structured and efficient databases. The above guide should set you on course for implementing basic database operations using Room's powerful abstraction over SQLite.