在 android studio 中使用 Kotlin 和 Room 构建错误

问题描述 投票:0回答:1

我正在为学校制作一个 android studio 应用程序,需要使用 room db,我想尝试使用 kotlin,现在我遇到了 Room 注释和 kotlin 调试的问题

我很简单地尝试运行应用程序来创建数据库,但出了点问题

这是 build.gradle(:app)

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id "com.google.devtools.ksp"
}



android {
    namespace 'com.example.lordofthegames'
    compileSdk 33

    defaultConfig {
        applicationId "com.example.lordofthegames"
        minSdk 21
        targetSdk 33
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        resources.excludes.add("META-INF/*")
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        viewBinding true
    }


}
/*
configurations.all {
    resolutionStrategy {
        eachDependency {
            if ((requested.group == "org.jetbrains.kotlin") && (requested.name.startsWith("kotlin-stdlib"))) {
                useVersion("1.8.0")
            }
        }
    }
}*/

dependencies {
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.8.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'androidx.fragment:fragment:1.5.5'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'

    implementation('com.google.android.material:material:1.8.0')
    implementation('androidx.core:core-ktx:1.9.0')
    implementation('androidx.navigation:navigation-ui-ktx:2.5.3')
    implementation('androidx.navigation:navigation-fragment:2.5.3')

    implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10")

    def room_version = "2.5.0"

    implementation("androidx.room:room-runtime:$room_version")
    annotationProcessor("androidx.room:room-compiler:$room_version")

    // To use Kotlin Symbol Processing (KSP)
    ksp("androidx.room:room-compiler:$room_version")

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation("androidx.room:room-ktx:$room_version")

    // optional - RxJava2 support for Room
    implementation("androidx.room:room-rxjava2:$room_version")

    // optional - RxJava3 support for Room
    implementation("androidx.room:room-rxjava3:$room_version")

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation("androidx.room:room-guava:$room_version")

    // optional - Test helpers
    testImplementation("androidx.room:room-testing:$room_version")

    // optional - Paging 3 Integration
    implementation("androidx.room:room-paging:$room_version")

}

build.gradle(AppName)

buildscript {
    ext.kotlin_version = '1.6.0-RC'
    ext {
        compose_version = '1.0.1'
        fragment_version = "1.3.6"
    }
    repositories {
        google()
        mavenCentral()
        maven {
            url = uri("https://plugins.gradle.org/m2/")
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.3.1'
        //classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.21"
        //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
    }
}

plugins {
    id 'com.android.application' version '7.3.1' apply false
    id 'com.android.library' version '7.3.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.7.20' apply false
    id "com.google.devtools.ksp" version "1.8.10-1.0.9" apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}

设置.gradle

pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}
rootProject.name = "LordOfTheGames"
include ':app'

和 gradle.properties

# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx4068m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
kapt.verbose=false
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
android.enableJetifier=true

最后是构建错误,因为我真的不知道这些错误是什么

Executing tasks: [:app:assembleDebug] in project C:\[...]\LordOfTheGames-MobileApp\LordOfTheGames

Configuration 'kspDebugKotlinProcessorClasspath' was resolved during configuration time.
This is a build performance and scalability issue.
See https://github.com/gradle/gradle/issues/2298
Run with --info for a stacktrace.
Unable to decide if config caching is enabled
java.lang.NoSuchMethodError: 'org.gradle.internal.buildoption.BuildOption$Value 
> Task :app:checkDebugDuplicateClasses FAILED
> Task :app:mergeDebugNativeLibs FAILED
> Task :app:compileDebugKotlin FAILED

FAILURE: Build completed with 3 failures.

1: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':app:checkDebugDuplicateClasses'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Failed to transform kotlin-android-extensions-1.6.10.jar (org.jetbrains.kotlin:kotlin-android-extensions:1.6.10) to match attributes {artifactType=enumerated-runtime-classes, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}.
      > Execution failed for JetifyTransform: C:\Users\vanni\.gradle\caches\modules-2\files-2.1\org.jetbrains.kotlin\kotlin-android-extensions\1.6.10\e61216589e513d39a8976573c83afc8784b4b6d\kotlin-android-extensions-1.6.10.jar.
         > Failed to transform 'C:\Users\vanni\.gradle\caches\modules-2\files-2.1\org.jetbrains.kotlin\kotlin-android-extensions\1.6.10\e61216589e513d39a8976573c83afc8784b4b6d\kotlin-android-extensions-1.6.10.jar' using Jetifier. Reason: AmbiguousStringJetifierException, message: The given artifact contains a string literal with a package reference 'android.support.v4' that cannot be safely rewritten. Libraries using reflection such as annotation processors need to be updated manually to add support for androidx.. (Run with --stacktrace for more details.)
           This is a known exception, and Jetifier won't be able to jetify this library.
           Suggestions:
            - If you believe this library doesn't need to be jetified (e.g., if it already supports AndroidX, or if it doesn't use support libraries/AndroidX at all), add android.jetifier.ignorelist = {comma-separated list of regular expressions (or simply names) of the libraries that you don't want to be jetified} to the gradle.properties file.
            - If you believe this library needs to be jetified (e.g., if it uses old support libraries and breaks your app if it isn't jetified), contact the library's authors to update this library to support AndroidX and use the supported version once it is released.
           If you need further help, please leave a comment at https://issuetracker.google.com/issues/140747218.

[...]
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':app:mergeDebugNativeLibs'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Failed to transform kotlin-android-extensions-1.6.10.jar (org.jetbrains.kotlin:kotlin-android-extensions:1.6.10) to match attributes {artifactType=android-jni, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}.
      > Execution failed for JetifyTransform: C:\Users\vanni\.gradle\caches\modules-2\files-2.1\org.jetbrains.kotlin\kotlin-android-extensions\1.6.10\e61216589e513d39a8976573c83afc8784b4b6d\kotlin-android-extensions-1.6.10.jar.
         > Failed to transform 'C:\Users\vanni\.gradle\caches\modules-2\files-2.1\org.jetbrains.kotlin\kotlin-android-extensions\1.6.10\e61216589e513d39a8976573c83afc8784b4b6d\kotlin-android-extensions-1.6.10.jar' using Jetifier. Reason: AmbiguousStringJetifierException, message: The given artifact contains a string literal with a package reference 'android.support.v4' that cannot be safely rewritten. Libraries using reflection such as annotation processors need to be updated manually to add support for androidx.. (Run with --stacktrace for more details.)
           This is a known exception, and Jetifier won't be able to jetify this library.
           Suggestions:
            - If you believe this library doesn't need to be jetified (e.g., if it already supports AndroidX, or if it doesn't use support libraries/AndroidX at all), add android.jetifier.ignorelist = {comma-separated list of regular expressions (or simply names) of the libraries that you don't want to be jetified} to the gradle.properties file.
            - If you believe this library needs to be jetified (e.g., if it uses old support libraries and breaks your app if it isn't jetified), contact the library's authors to update this library to support AndroidX and use the supported version once it is released.
           If you need further help, please leave a comment at https://issuetracker.google.com/issues/140747218.

[...]

==============================================================================

3: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> 'compileDebugJavaWithJavac' task (current target is 11) and 'compileDebugKotlin' task (current target is 1.8) jvm target compatibility should be set to the same Java version.
  Consider using JVM toolchain: https://kotl.in/gradle/jvm/toolchain

[...]

==============================================================================

代码是

DAO

package com.example.lordofthegames.Database

import android.provider.ContactsContract.CommonDataKinds.Note
import androidx.lifecycle.LiveData
import androidx.room.*
import com.example.lordofthegames.db_entities.*
import com.example.lordofthegames.recyclerView.GameCardItem
import kotlinx.coroutines.flow.Flow
import java.util.*

@Dao
interface LOTGDAO {

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insertAchievement(achievement: Achievement)

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insertCategory(category: GameCategory)

    @Insert
    fun insertComment(comments: Comments)

}

数据库

package com.example.lordofthegames.Database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.example.lordofthegames.db_entities.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

@Database(entities =
arrayOf(Game::class,
                    Achievement::class,
                    Categories::class,
                    Notes::class,
                    GameCategory::class,
                    Discussion::class,
                    Comments::class)
                , version = 3, exportSchema = false)
@TypeConverters(DateConverter::class)
abstract class LOTGDatabase: RoomDatabase() {

    companion object {
        @Volatile
        private var INSTANCE: LOTGDatabase? = null

        val executor: ExecutorService = Executors.newFixedThreadPool(4)

        fun getDatabase(context: Context): LOTGDatabase {

            return INSTANCE ?: synchronized(this){
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    LOTGDatabase::class.java,
                    "lotgdb"
                ).build()
                INSTANCE = instance
                instance
            }
        }
    }
}

存储库

package com.example.lordofthegames.Database

import android.app.Application
import androidx.annotation.WorkerThread
import androidx.lifecycle.LiveData
import com.example.lordofthegames.db_entities.*
import java.util.*
import kotlinx.coroutines.flow.Flow


class LOTGRepository(
    private val lotgdao: LOTGDAO,
    var application: Application
    ) {
    val allGames: LiveData<List<Game>> = lotgdao.getAllGames()
    @Suppress("RedundantSuspendModifier")
    @WorkerThread
    suspend fun insertGame(game: Game){
        lotgdao.insertGame(game)
    }
}

我提前感谢任何有任何想法来解决这个问题的人,因为我花了两周的时间来解决它

我尝试搜索错误,但从

kapt
切换到
ksp
、添加或删除依赖项以及更新项目都没有任何变化

kotlin android-gradle-plugin build.gradle android-room
1个回答
0
投票

我不确定这是否与我遇到的错误完全相同(因为我在 dagger2 依赖项上苦苦挣扎),但我们查看日志,它显示:

1. java.lang.NoSuchMethodError: 'org.gradle.internal.buildoption.BuildOption$Value

2. 它确实提到我们在这里使用:“ksp”而不是 kapt

所以,我遇到了同样的问题,出现错误 java.lang.NoSuchMethodError 当尝试对 dagger2 依赖项执行相同操作时(从“kapt”移动到“ksp”

我使用以下Kotlin、AGP和KSP版本的组合解决了这个问题,如下:

id("com.android.application") version "**8.1.2**" apply false
id("org.jetbrains.kotlin.android") version "**1.9.10**" apply false
id("com.google.devtools.ksp") version "**1.9.10-1.0.13**" apply false

看看这是否有帮助(请注意:我使用的是 Kotlin 而不是 groovy

© www.soinside.com 2019 - 2024. All rights reserved.