Room Architecture Component Library

Room is a Jetpack architecture component library that simplifies database setup and access. It allows you to define your database structure and queries using annotated Kotlin classes.

Room is composed of an API, annotations, and a compiler. The API contains classes you extend to define your database and build an instance of it. You use the annotations to indicate things like which classes need to be stored in the database, which class represents your database, and which class specifies the accessor functions to your database tables. The compiler processes the annotated classes and generates the implementation of your database.

To use Room, you first need to add the dependencies it requires. Add the room-runtime and room-compiler dependencies to your app/build.gradle file.

Listing 11.1  Adding dependencies (app/build.gradle)

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

android {
    ...
}
...
dependencies {
    ...
    implementation 'androidx.core:core-ktx:1.1.0-alpha04'
    implementation 'androidx.room:room-runtime:2.1.0-alpha04'
    kapt 'androidx.room:room-compiler:2.1.0-alpha04'
    ...
}

Near the top of the file, you added a new Android Studio plug-in. Plug-ins are a way to add functionality to the IDE. Check out plugins.jetbrains.com/​androidstudio for more plug-ins you can add.

kotlin-kapt stands for Kotlin annotation processor tool. When libraries generate code for you, you will often want to use those generated classes directly in your code. But by default, those generated classes are not visible to Android Studio, so you will see an error if you try to import them. Adding the kotlin-kapt plug-in makes library-generated files visible to Android Studio so that you can import them in your own classes.

The first dependency you added, room-runtime, is for the Room API containing all the classes and annotations you will need to define your database. The second dependency, room-compiler, is for the Room compiler, which will generate your database implementation based on the annotations you specify. The compiler uses the kapt keyword, instead of implementation, so that the generated classes from the compiler are visible to Android Studio, thanks to the kotlin-kapt plug-in.

Do not forget to sync your Gradle files. With your dependencies in place, you can move on to preparing your model layer for storage in the database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.171.235