fun saveImageInFirebase(){
var currentUser =mAuth!!.currentUser
val email:String=currentUser!!.email.toString()
val storage=FirebaseStorage.getInstance()
val storgaRef=storage.getReferenceFromUrl("gs://gameudemy.appspot.com")
val df=SimpleDateFormat("ddMMyyHHmmss")
val dataobj=Date()
val imagePath= splitString(email) + "."+ df.format(dataobj)+ ".jpg"
val ImageRef=storgaRef.child("images/"+imagePath )
imageSpace.isDrawingCacheEnabled=true
imageSpace.buildDrawingCache()
val drawable=imageSpace.drawable as BitmapDrawable
val bitmap=drawable.bitmap
val baos=ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos)
val data= baos.toByteArray()
val uploadTask=ImageRef.putBytes(data)
uploadTask.addOnFailureListener{
Toast.makeText(applicationContext,"fail to upload",Toast.LENGTH_LONG).show()
}.addOnSuccessListener { taskSnapshot ->
var DownloadURL= taskSnapshot.storage.downloadUrl.toString()!!
myRef.child("Users").child(currentUser.uid).child("email").setValue(currentUser.email)
myRef.child("Users").child(currentUser.uid).child("ProfileImage").setValue(DownloadURL)
loadTweets()
}
}
The setValue method called turns red and says Unresolved reference.
How to resolve it?
Gradle structure->
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.4.10"
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.0"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'com.google.gms.google-services'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.shanu.sevenstar"
minSdkVersion 24
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
apply plugin: 'kotlin-android-extensions'
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
implementation 'com.google.firebase:firebase-analytics:17.6.0'
implementation 'com.google.firebase:firebase-core:17.5.1'
implementation 'com.google.firebase:firebase-auth:19.4.0'
implementation 'com.google.firebase:firebase-database:19.5.0'
implementation 'com.google.firebase:firebase-storage:19.2.0'
testImplementation 'junit:junit:4.13.1'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.8"
}
Error returned is
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline operator fun MutableMap<in String, in TypeVariable(V)>.setValue(thisRef: Any?, property: KProperty<>, value: TypeVariable(V)): Unit defined in kotlin.collections
public inline operator fun KMutableProperty0<TypeVariable(V)>.setValue(thisRef: Any?, property: KProperty<>, value: TypeVariable(V)): Unit defined in kotlin
public inline operator fun <T, V> KMutableProperty1<TypeVariable(T), TypeVariable(V)>.setValue(thisRef: TypeVariable(T), property: KProperty<*>, value: TypeVariable(V)): Unit defined in kotlin
I have following build.gradle file under project :
buildscript {
ext.kotlin_version = '1.3.11'
ext.gradle_version = '3.2.1'
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:$gradle_version"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
And here is my build.gradle under app module:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
androidExtensions {
experimental = true
}
android {
compileSdkVersion rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "com.sample.android.tmdb"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
buildConfigField "String", "TMDB_API_KEY", "\"${getProperty("local.properties", "tmdb_api_key")}\""
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
// Support libraries
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "com.android.support:appcompat-v7:$supportLibraryVersion"
implementation "com.android.support:design:$supportLibraryVersion"
implementation "com.android.support:recyclerview-v7:$supportLibraryVersion"
implementation "com.android.support:cardview-v7:$supportLibraryVersion"
implementation "com.android.support:palette-v7:$supportLibraryVersion"
implementation 'com.android.support.constraint:constraint-layout:2.0.0-alpha2'
// Architecture components
implementation "android.arch.paging:runtime:$pagingVersion"
implementation "android.arch.lifecycle:runtime:$lifecycleVersion"
implementation "android.arch.lifecycle:extensions:$lifecycleVersion"
// Gson
implementation 'com.google.code.gson:gson:2.8.5'
// Retrofit
implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion"
implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion"
// Dagger
implementation "com.google.dagger:dagger:$daggerVersion"
kapt "com.google.dagger:dagger-compiler:$daggerVersion"
implementation "com.google.dagger:dagger-android:$daggerVersion"
implementation "com.google.dagger:dagger-android-support:$daggerVersion"
kapt "com.google.dagger:dagger-android-processor:$daggerVersion"
//Android RX
implementation "io.reactivex.rxjava2:rxjava:$rxjavaVersion"
implementation "io.reactivex.rxjava2:rxandroid:$rxandroidVersion"
// Network
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.0'
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation "com.github.bumptech.glide:glide:$glideVersion"
kapt "com.github.bumptech.glide:compiler:$glideVersion"
// Timber
implementation 'com.jakewharton.timber:timber:4.7.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
def getProperty(String filename, String propName) {
def propsFile = rootProject.file(filename)
if (propsFile.exists()) {
def props = new Properties()
props.load(new FileInputStream(propsFile))
if (props[propName] != null) {
return props[propName]
} else {
print("No such property " + propName + " in file " + filename)
}
} else {
print(filename + " does not exist!")
}
}
I get following error when I build the project :
Failed to resolve: adapters
Failed to resolve: library
Failed to resolve: runtime
Failed to resolve: palette-v7
Failed to resolve: common
How can I resolve it?
Project can be found at : https://github.com/Ali-Rezaei/TMDb-Paging
Addenda:
I just change 4.6 version to 4.4:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
And gradle_version = '3.1.4' and it worked as expected.
I am trying to implement Room into Android application written in Kotlin. After build failing so many times, I pinpointed the problem that it failed when I added #Database into my database class.
package sample.service.local
import android.arch.persistence.room.Database
import android.arch.persistence.room.RoomDatabase
import sample.service.model.Announcement
#Database(entities = [Announcement::class], version = 1)
abstract class AnnounceDatabase: RoomDatabase() {
abstract fun announceDAO(): AnnounceDAO
}
If I commented out the line with #Database it built successfully. Its DAO and Entity files shouldn't be the problem as I tried building with them without #Database and it was successful. I also haven't added them into any other classes; I just created 3 new files which are this database, its dao, and its entity.
Here's build.gradle(Module:app)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: "kotlin-kapt"
android {
compileSdkVersion 27
defaultConfig {
applicationId "sample"
minSdkVersion 16
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
dataBinding.enabled true
}
}
project.ext {
supportLibraryVersion = "26.1.0"
daggerVersion = "2.13"
butterKnifeVersion = "8.8.1"
rxJavaVersion = "2.1.0"
rxAndroidVersion = "2.0.1"
lifecycleVersion = "1.0.0"
roomVersion = "1.0.0"
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.google.android.gms:play-services-maps:11.8.0'
implementation 'com.android.support:support-v4:27.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
// Android Support Library
implementation 'com.android.support:design:27.1.0'
implementation 'com.google.android.gms:play-services-location:11.8.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:cardview-v7:27.1.0'
implementation 'com.android.support:recyclerview-v7:27.1.0'
implementation 'com.android.support:support-annotations:27.1.0'
implementation 'com.android.support:support-compat:27.1.0'
implementation 'com.android.support:support-core-ui:27.1.0'
// Easy Permission
implementation 'pub.devrel:easypermissions:1.2.0'
// Lifecycle
implementation "android.arch.lifecycle:extensions:1.1.0"
annotationProcessor "android.arch.lifecycle:compiler:1.1.0"
// Kotlin binding
// kapt 'com.android.databinding:compiler:3.1.0'
// Dagger core
kapt "com.google.dagger:dagger-compiler:$project.daggerVersion"
implementation "com.google.dagger:dagger:$project.daggerVersion"
// Dagger Android
kapt "com.google.dagger:dagger-android-processor:$project.daggerVersion"
implementation "com.google.dagger:dagger-android-support:$project.daggerVersion"
// Timber
implementation 'com.jakewharton.timber:timber:4.6.0'
// Simple Item Decoration
implementation 'com.bignerdranch.android:simple-item-decoration:1.0.0'
// Retrofit
implementation "com.squareup.retrofit2:retrofit:2.1.0"
implementation "com.squareup.retrofit2:converter-gson:2.1.0"
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
// implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
// RxJava & RxAndroid
implementation 'io.reactivex.rxjava2:rxjava:2.1.12'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
// PageIndicatorView
implementation 'com.romandanylyk:pageindicatorview:1.0.0#aar'
// Room
implementation "android.arch.persistence.room:rxjava2:$project.roomVersion"
implementation "android.arch.persistence.room:runtime:$project.roomVersion"
kapt "android.arch.persistence.room:compiler:$project.roomVersion"
testImplementation "android.arch.persistence.room:testing:$project.roomVersion"
}
Here's project's gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.2.31'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
I ran gradlew clean build --stacktrace --debug and here's error message
Any help will be appreciated.
The problem is in my Entity class where I used val instead of var for the parameters, so I just changed all of them to var and the problem is solved.
Edit: My DAO class also has a problem as well where ArrayList cannot be used instead of List
I am implementing Room persistence lib in kotlin for my database implementation.
Following are my Entity, Dao and Database classes:
Food.kt
#Entity
class Food(#ColumnInfo(name = "food_name") var foodName: String,
#ColumnInfo(name = "food_desc") var foodDesc: String,
#ColumnInfo(name = "protein") var protein: Double,
#ColumnInfo(name = "carbs") var carbs: Double,
#ColumnInfo(name = "fat") var fat: Double)
{
#ColumnInfo(name = "id")
#PrimaryKey(autoGenerate = true)
var id: Long = 0
#ColumnInfo(name = "calories")
var calories: Double = 0.toDouble()
}
PersonalizedFood.kt
#Entity(primaryKeys = arrayOf("food_id","date"))
class PersonalizedFood(#ColumnInfo(name = "quantity") var quantity: Int,
#ColumnInfo(name = "unit") var unit: String,
#ColumnInfo(name = "date") var date: Date){
#ColumnInfo(name = "food_id")
var foodId:Long = 0
}
FoodDao.kt
#Dao
interface FoodDao {
companion object{
const val ID = "id"
const val NAME = "name"
const val PROTEIN = "protein"
const val DESC = "desc"
const val CARBS = "carbs"
const val FAT = "fat"
const val DATE = "date"
const val FOOD_ID = "food_id"
const val ALL_FOOD_LIST = "food"
const val PERSONALISED_FOOD_LIST = "personalised_food"
}
/**
* Returns food details of a food given by food_id
*/
#Query("SELECT * FROM $ALL_FOOD_LIST WHERE $ID=:food_id")
fun getFoodDetails(food_id:Long):Food
/**
* Inserts food items in all_food_list
*/
#Insert
fun addFoodList(list:ArrayList<Food>)
#Insert(onConflict = REPLACE)
fun saveFood(food:PersonalizedFood)
#Query("SELECT * FROM $PERSONALISED_FOOD_LIST WHERE $FOOD_ID=:foodId and $DATE=:date")
fun getFood(foodId:Int, data:Date):PersonalizedFood
#Query("SELECT * FROM $ALL_FOOD_LIST where $ID in (select $FOOD_ID from $PERSONALISED_FOOD_LIST where $DATE = :date)")
fun getFood(date:Date):ArrayList<Food>
}
Converter.kt
class Converter {
companion object{
#TypeConverter
fun fromTimestamp(value: Long?): Date? {
return if (value == null) null else Date(value)
}
#TypeConverter
fun dateToTimestamp(date: Date): Long {
return date.time
}
}
}
FoodDatabase.kt
#Database(entities = arrayOf(Food::class, PersonalizedFood::class), version = 1)
#TypeConverters(Converter::class)
abstract class FoodDatabase : RoomDatabase(){
abstract fun foodDao():FoodDao
companion object{
private val databaseName = "diet"
var dbInstance:FoodDao? = null
fun getInstance(context:Context):FoodDao?{
if(dbInstance == null)
dbInstance = Room.inMemoryDatabaseBuilder(context, FoodDatabase::class.java).build().foodDao()
return dbInstance;
}
}
}
And when i run following code to create database:
FoodDatabase.getInstance(baseContext)?.getFood(Calendar.getInstance().time)
It gives me following exception:
Caused by: java.lang.RuntimeException: cannot find implementation for
com.chandilsachin.diettracker.database.FoodDatabase. FoodDatabase_Impl
does not exist
at
android.arch.persistence.room.Room.getGeneratedImplementation(Room.java:90)
at
android.arch.persistence.room.RoomDatabase$Builder.build(RoomDatabase.java:340)
at
com.chandilsachin.diettracker.database.FoodDatabase$Companion.getInstance(FoodDatabase.kt:21)
at
com.chandilsachin.diettracker.MainActivity$SetUpFoodDatabase.doInBackground(MainActivity.kt:95)
at
com.chandilsachin.diettracker.MainActivity$SetUpFoodDatabase.doInBackground(MainActivity.kt:77)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Has anyone implemented room persistence in kotlin?
Edited
This question was marked duplicate of this. Though problem statement is same but solution given does not solve my problem. Solution says i have to add replace annotationProcessor to kapt "android.arch.persistence.room:compiler:1.0.0-alpha1" dependency. I made those changes and it resulted in gradle error while project build.
Information:Gradle tasks [:app:assembleDebug] Warning:warning:
Supported source version 'RELEASE_7' from annotation processor
'android.arch.persistence.room.RoomProcessor' less than -source '1.8'
Warning:warning: The following options were not recognized by any
processor: '[kapt.kotlin.generated]'
/Users/BBI-M1025/Documents/BBI/Workspace_fun/Android/diet-tracker/app/src/main/java/com/chandilsachin/diettracker/database/Food.kt
Error:(1, 1) Some error(s) occurred while processing annotations. Please see the error messages above.
Error:Execution failed for task ':app:kaptDebugKotlin'.
Compilation error. See log for more details
Information:BUILD FAILED in 10s
Information:2 errors
Information:2 warnings
Information:See complete output in console
I am attaching my gradle file also:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.chandilsachin.diettracker"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha8'
compile 'com.android.support:cardview-v7:25.0.1'
compile 'com.android.support:recyclerview-v7:25.0.1'
compile 'com.github.ne1c:rainbowmvp:1.2.1'
compile "org.jetbrains.anko:anko-commons:0.10.0"
/*annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1"
compile "android.arch.lifecycle:extensions:1.0.0-alpha1"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha1"*/
compile "android.arch.persistence.room:runtime:1.0.0-alpha1"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1"
kapt "android.arch.persistence.room:compiler:1.0.0-alpha1"
testCompile 'junit:junit:4.12'
}
repositories {
mavenCentral()
}
Has anyone come across this issue?
After spinning my head around for a while with this problem, I came across to the solution.
It was really hard as there is no official tutorial, blog etc out there to help with this problem as of now.
I had to do several hit and trial for all the combination of gradle plugins and dependencies as i knew that something is wrong with gradle config only.
Lets come to the solution:
I had to remove apply plugin: 'kotlin-kapt' from build.gradle(:module) file
and replace annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1" to kapt "android.arch.persistence.room:compiler:1.0.0-alpha1".
This is the gradle configuration to successfully compile code.
But there more things to check. You have to initialise properties of your #Entity class unlike java given in Room Persistence lib doc. Though there are getter setter but it is not mentioned to create a constructor with initialisation.
So I had to change my #Entity class with this:
#Entity(tableName = "all_food_list")
class Food (#ColumnInfo(name = "food_name") var foodName: String = "",
#ColumnInfo(name = "food_desc") var foodDesc: String = "",
#ColumnInfo(name = "protein") var protein: Double = 0.0,
#ColumnInfo(name = "carbs") var carbs: Double = 0.0,
#ColumnInfo(name = "fat") var fat: Double = 0.0,
#ColumnInfo(name = "calories") var calories: Double = 0.0)
{
#ColumnInfo(name = "id")
#PrimaryKey(autoGenerate = true)
var id: Long = 0
}
Now for TypeConverts, Unlike java, you need to create normal function not static functions(companion object):
class Converters{
#TypeConverter
fun fromTimestamp(value: String): Calendar {
val arr = value.split("-")
val cal = Calendar.getInstance()
cal.set(arr[0].toInt(), arr[1].toInt(), arr[2].toInt())
return cal
}
#TypeConverter
fun dateToTimestamp(date: Calendar): String {
return "${date.get(Calendar.DATE)}-${date.get(Calendar.MONTH)+1}-${date.get(Calendar.YEAR)}"
}
}
I am adding build.gradle file also to make it more clear:
build.gradle(:project)
buildscript {
ext.kotlin_version = '1.1.2-4'
ext.gradle_version_stable = '2.3.2'
ext.gradle_version_preview = '3.0.0-alpha1'
ext.anko_version = '0.10.0'
repositories {
maven { url 'https://maven.google.com' }
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-alpha1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
maven { url 'https://maven.google.com' }
jcenter()
maven { url "https://jitpack.io" }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
build.gradle(:module)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.chandilsachin.diettracker"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
...
...
// room persistence dependency
compile "android.arch.persistence.room:runtime:1.0.0-alpha1"
kapt "android.arch.persistence.room:compiler:1.0.0-alpha1"
testCompile 'junit:junit:4.12'
}
repositories {
mavenCentral()
}
I think this is all, I did to make my code woking.
Hope this helps someone else also.
Here my gradle files, i didn't need to add thoses plugins.
build.gradle(project):
buildscript {
ext.kotlin_version = '1.1.2-4'
ext.lifecycle_version = '1.0.0-alpha1'
ext.room_version = '1.0.0-alpha1'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
build.gradle (app)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
//enable anotation processing with kotlin, disabled by default
kapt {
generateStubs = true
}
android {
/**
...
**/
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
//kotlin
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
//support
compile 'com.android.support:appcompat-v7:25.3.1'
//google architecture
compile "android.arch.lifecycle:runtime:$lifecycle_version"
compile "android.arch.lifecycle:extensions:$lifecycle_version"
annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version"
kapt "android.arch.lifecycle:compiler:$lifecycle_version"
//database
compile "android.arch.persistence.room:runtime:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:$room_version"
kapt "android.arch.persistence.room:compiler:$room_version"
}
repositories {
mavenCentral()
}
Then run menu build-> make project to create impl class.
Hope this helps
I made an example similar using Java and used to have same problem and solution was add APT line apt "android.arch.persistence.room:compiler:1.0.0-alpha1"
without apply: apply plugin: 'kotlin-kapt'. Remove this line!!
You have to clear project and rebuild it before run again and try uninstall existing app on phone or Virtual device.
Hope you help.
I got the same issue when I try to migrate from Java to Kotlin:
RuntimeException: cannot find implementation for AppDatabase. AppDatabase_Impl does not exist
I tried all these answers in this question, none all them works, then I found an article: Kotlinlang Tutorials - Android Frameworks Using Annotation Processing:
In Kotlin you specify the dependencies in a similar to Java way using Kotlin Annotation processing tool (kapt) instead of annotationProcessor.
Then I modified the build.gradle(Module:app) by changing all annotationProcessor to kapt, it works:
--- a/app/build.gradle
+++ b/app/build.gradle
## -2,6 +2,8 ## apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
+apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
android {
// Butter Knife
implementation "com.jakewharton:butterknife:$butterknife_version"
- annotationProcessor "com.jakewharton:butterknife-compiler:$butterknife_version"
+ kapt "com.jakewharton:butterknife-compiler:$butterknife_version"
// Room
implementation "android.arch.persistence.room:runtime:$arch_lifecycle_version"
- annotationProcessor "android.arch.persistence.room:compiler:$arch_lifecycle_version"
+ kapt "android.arch.persistence.room:compiler:$arch_lifecycle_version"
// LifeCycle
implementation "android.arch.lifecycle:runtime:$arch_lifecycle_version"
implementation "android.arch.lifecycle:extensions:$arch_lifecycle_version"
implementation "android.arch.lifecycle:common-java8:$arch_lifecycle_version"
- annotationProcessor "android.arch.lifecycle:compiler:$arch_lifecycle_version"
+ kapt "android.arch.lifecycle:compiler:$arch_lifecycle_version"
// Dagger
implementation "com.google.dagger:dagger:$dagger_version"
implementation "com.google.dagger:dagger-android-support:$dagger_version"
- annotationProcessor "com.google.dagger:dagger-compiler:$dagger_version"
- annotationProcessor "com.google.dagger:dagger-android-processor:$dagger_version"
+ kapt "com.google.dagger:dagger-compiler:$dagger_version"
+ kapt "com.google.dagger:dagger-android-processor:$dagger_version"
}
If you use Butter Knife, you should also change to kapt, otherwise the views which are injected might be null.
in the Dao interface check that the annotations like #Query .. are imported from the room database class and not from somewhere else
Dagger2 does not create classes Dagger*. I created the interface MyContainerComponent, but the class DaggerMyContainerComponent not created!
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
classpath "com.android.databinding:dataBinder:1.0-rc4"
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
classpath 'com.frogermcs.androiddevmetrics:androiddevmetrics-plugin:0.4'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.6"
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
in build.gradle
apply plugin: 'com.android.application'
apply plugin: 'android-apt'
apply plugin: 'com.android.databinding'
apply plugin: 'kotlin-android'
apply plugin: 'com.frogermcs.androiddevmetrics'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.tegra.module.profile"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.1.1'
testCompile 'junit:junit:4.12'
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
kapt 'com.android.databinding:compiler:1.0-rc4'
//dagger
compile 'com.google.dagger:dagger:2.8'
apt 'com.google.dagger:dagger-compiler:2.8'
provided 'javax.annotation:jsr250-api:1.0'
//glide
compile 'com.github.bumptech.glide:glide:3.7.0'
//rxAndroid
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.1.6'
//autoFactory
compile group: 'com.google.auto.factory', name: 'auto-factory', version: '1.0-beta3'
//retrofit
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile group: 'com.squareup.retrofit2', name: 'adapter-rxjava', version: '2.1.0'
//OkHttp
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
//timber
compile 'com.jakewharton.timber:timber:4.5.1'
//stetho
compile 'com.facebook.stetho:stetho:1.4.2'
compile 'com.facebook.stetho:stetho-okhttp3:1.4.2'
//constraint-layout
compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
}
kapt {
generateStubs = true
}
MyContainerComponent.kt
package com.tegra.module.profile.ioc
#Component(modules = arrayOf(ProfileModule::class))
#Singleton
public interface MyContainerComponent {
fun inject(profileActivity: ProfileActivity)
}
ProfileModule.kt
package com.tegra.module.profile.bl.di
#Module
class ProfileModule(val application: Application) {
#Provides
#Singleton
fun provideApplication(): Application {
return application
}
#Provides
#Singleton
fun provideContext(): Context {
return application
}
}
Any solutions? Already tried to: change gradle version, Clean, Rebuild, Change dependecy versions, also deleting the Gradle cache and reinstalling Android Studio.
In order to use Dagger annotations in Kotlin files you have to use kapt for Dagger compiler:
kapt 'com.google.dagger:dagger-compiler:2.8'
Also, delete all apt dependencies because kapt handles annotations in Java too.
Official docs