Kotlin + Room:注释处理时出错

时间:2018-04-15 16:12:06

标签: android kotlin android-room

我没有找到真正的解决方案而面临以下问题。我试着添加Room库而没有运气。我一直都会收到这个错误:

    e: java.lang.IllegalStateException: failed to analyze: org.jetbrains.kotlin.kapt3.diagnostic.KaptError: Error while annotation processing
    at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:137)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:158)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:61)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:107)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:386)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:892)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:919)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:891)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:385)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.jetbrains.kotlin.kapt3.diagnostic.KaptError: Error while annotation processing
    at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:90)
    at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:42)
    at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:205)
    at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:166)
    at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:82)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:96)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:106)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:83)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:376)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:67)
    at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:96)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:367)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:132)
    ... 30 more

:app:kaptDevDebugKotlin FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDevDebugKotlin'.
> Internal compiler error. See log for more details

这是我的build.gradle(模块)

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 26

    defaultConfig {
        applicationId "com.xxx.xxx"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }


    productFlavors {
        dev {
            // dev utilizes minSDKVersion = 21 to allow the Android gradle plugin
            // to pre-dex each module and produce an APK that can be tested on
            // Android Lollipop without time consuming dex merging processes.
            minSdkVersion 16
            buildConfigField "String", "URL_BASE", "\"https://www.xxxxx.com\""
        }
        prod {
            minSdkVersion 16
            buildConfigField "String", "URL_BASE", "\"https://www.xxxxx.com\""
        }

    }

    defaultConfig{
        multiDexEnabled true
    }

    lintOptions{
        abortOnError false
    }


    packagingOptions {
        exclude 'META-INF/rxjava.properties'
    }

    flavorDimensions "default"

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

buildscript {
    ext.supportVersion = '26.0.2'
    ext.appcompat_version = '26.0.2'
    ext.retrofitVersion = '2.3.0'
    ext.rxVersion = '2.0.2'
    ext.rxAndroidVersion = '2.0.1'
    ext.rxKotlinVersion = '2.0.0'
    ext.okhttpVersion = '3.8.1'
    ext.multidexVersion = '1.0.1'
    ext.gsonVersion = '2.8.0'
    ext.inappBillingVersion = '1.0'
    ext.picassoVersion = '2.5.2'
    ext.circleImageViewVersion = '2.1.0'
    ext.tedPermissionsVersion = '2.1.0'
    ext.firebaseAuthVersion = '2.3.0'
    ext.firebaseCoreVersion = '11.0.4'
    ext.rxLifeCycleVersion = '2.2.1'
    ext.circleImageViewVersion = '2.1.0'
    ext.picassoVersion = '2.5.2'
    ext.parcelerVersion = '1.1.9'
    ext.glideVersion = '4.6.1'
    ext.roomVersion = '1.0.0'

    repositories {
        mavenCentral()
        jcenter()
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    //Framework
    compile "com.android.support:appcompat-v7:$supportVersion"
    compile "com.android.billingclient:billing:$inappBillingVersion"
    compile "com.firebaseui:firebase-ui-auth:$firebaseAuthVersion"
    compile "com.google.firebase:firebase-core:$firebaseCoreVersion"
    compile "com.android.support:support-v4:$supportVersion"

    //Room
    compile "android.arch.persistence.room:runtime:$roomVersion"
    compile "android.arch.persistence.room:rxjava2:$roomVersion"
    kapt "android.arch.persistence.room:compiler:$roomVersion"

    //Kotlin
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    //Rx & Retrofit 2 **********************************
    compile("com.squareup.retrofit2:retrofit:$retrofitVersion") {
        // exclude Retrofit’s OkHttp peer-dependency module and define your own module import
        exclude module: 'okhttp'
    }
    compile "com.squareup.retrofit2:converter-gson:$retrofitVersion"
    compile "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion"
    compile "io.reactivex.rxjava2:rxkotlin:$rxKotlinVersion"
    compile "com.squareup.okhttp3:okhttp:$okhttpVersion"
    compile "com.squareup.okhttp3:logging-interceptor:$okhttpVersion"
    compile "io.reactivex.rxjava2:rxandroid:${rxAndroidVersion}"
    compile "io.reactivex.rxjava2:rxjava:$rxVersion"
    compile "com.trello.rxlifecycle2:rxlifecycle:$rxLifeCycleVersion"
    compile "com.trello.rxlifecycle2:rxlifecycle-android-lifecycle-kotlin:$rxLifeCycleVersion"
    compile "com.trello.rxlifecycle2:rxlifecycle-components:$rxLifeCycleVersion"

    //others
    compile "com.squareup.picasso:picasso:$picassoVersion"
    compile "gun0912.ted:tedpermission-rx2:$tedPermissionsVersion"
    compile "de.hdodenhof:circleimageview:$circleImageViewVersion"
    compile "com.squareup.picasso:picasso:$picassoVersion"
    implementation "com.github.bumptech.glide:glide:$glideVersion"
    kapt "com.github.bumptech.glide:compiler:$glideVersion"

    //Parceler
    compile "org.parceler:parceler-api:$parcelerVersion"
    kapt "org.parceler:parceler:$parcelerVersion"

    //testing
    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'
}

kapt {
    generateStubs = true
    arguments {
        arg("realm.ignoreKotlinNullability", true)
    }
}

repositories {
    mavenCentral()
}

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '26.0.2'
            }
        }
    }
}

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

实体:

import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import org.parceler.Parcel


@Parcel
@Entity (tableName = "thumbnails")
data class Thumbnails(
        @ColumnInfo(name = "id")
        @PrimaryKey(autoGenerate = true)
        open var id: Long = 0,
        @ColumnInfo(name = "profile")
        open var profile: String? = "",
        @ColumnInfo(name = "contact")
        open var contact: String? = ""
)

MyDao课程:

@Dao
interface MyDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertItem(items : List<Item>)


    @Query("SELECT * FROM thumbnails WHERE id = :id")
    fun getItemById(id : Int) : Single<Item>
}

我的数据库:

@Database (entities = arrayOf(Thumbnails::class), version = 1)
abstract class MyDataBase : RoomDatabase()  {
    abstract fun myDao() : MyDao
}

从应用程序创建实例:

class AppDelegate : Application() {

    companion object {
        var appContext : Context? = null
        var prefs : SharedPreferencesManager? = null
        var db : MyDataBase? = null
    }

    override fun onCreate() {
        super.onCreate()

        prefs = SharedPreferencesManager(appContext)
        db = Room.databaseBuilder(this, MyDataBase::class.java, "my_database").build()

    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        appContext = base
    }
}

嗯,这个错误并不清楚,我一直试图找到解决方案。

如果我删除MyDatabase类,则构建过程会成功结束。我认为这个课程存在问题,但我找不到它。

1 个答案:

答案 0 :(得分:0)

好的,问题出在MyDao课上。函数getItemById返回了错误的类型。我推出了Item,我需要返回Thumbnails类

@Query("SELECT * FROM thumbnails WHERE id = :id")
    fun getItemById(id : Int) : Single<Thumbnails>