Android Room Persistence library and Kotlin
Usually in project build.gradle
I define the dependencies versions:
ext { buildToolsVersion = '25.0.2' supportLibVersion = '25.3.1' espressoVersion = '2.2.2' archRoomVersion = '1.0.0-alpha1'}
so in app build.gradle
the dependencies look like:
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" compile "com.android.support:appcompat-v7:${rootProject.supportLibVersion}" compile "android.arch.persistence.room:runtime:${rootProject.archRoomVersion}" annotationProcessor "android.arch.persistence.room:compiler:${rootProject.archRoomVersion}" kapt "android.arch.persistence.room:compiler:${rootProject.archRoomVersion}" androidTestCompile("com.android.support.test.espresso:espresso-core:${rootProject.espressoVersion}", { exclude group: 'com.android.support', module: 'support-annotations' }) testCompile 'junit:junit:4.12'}
Now you can define Entities Daos and Database in Kotlin.
Database:
@Database(entities = arrayOf(User::class), version = 1)abstract class Database : RoomDatabase() { abstract fun userDao(): UserDao}
Entity:
@Entity(tableName = "user")class User { @PrimaryKey(autoGenerate = true) var id: Int = 0 var name: String = ""}
Dao:
@Daointerface UserDao { @Query("SELECT * FROM user") fun getAll(): List<User> @Insert fun insertAll(vararg users: User) @Delete fun delete(user: User)}
NB: Query with parameters.Kotlin renames params, so the SQL query to retrieve all the emails that belong at an user via the userId is:
@Query("SELECT * FROM email " + "INNER JOIN user ON user.id = email.userId " + "WHERE user.id = :arg0") fun getEmailsForUser(userId: Int): List<Email>
In my case, in build.gradle, when you have "annotationProcessor" you need to duplicate with "kapt" and it works.
compile "android.arch.persistence.room:runtime:$room_version"annotationProcessor "android.arch.persistence.room:compiler:$room_version"kapt "android.arch.persistence.room:compiler:$room_version"
Try out these steps
Step 1. Set the room_version
in the project.gradle
file
buildscript { ext.kotlin_version = '1.1.51' ext.room_version = '1.0.0-alpha9-1'...
Step 2. Apply the kotlin-kapt
plugin in the app.gradle
file, and this solved my issue.
apply plugin: 'com.android.application'apply plugin: 'kotlin-android'apply plugin: 'kotlin-android-extensions'apply plugin: 'kotlin-kapt'android { compileSdkVersion 26 buildToolsVersion "26.0.1"...
Step 3. Add the kapt
dependency in the app.gradle
file
dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation "android.arch.persistence.room:runtime:$room_version" annotationProcessor "android.arch.persistence.room:compiler:$room_version" kapt "android.arch.persistence.room:compiler:$room_version"...}