我正在 Kotlin(Jetpack Compose)中开发一个简单的应用程序,但在解决运行我的应用程序时出现的问题时遇到问题。从我个人的理解来看,这不太好,在我看来,该功能应该按预期工作,但我仍然不确定代码本身或依赖项是否存在问题。根据 logcat,我试图在 MainActivity 中声明的数据库似乎无法识别/创建。我尝试通过使用 ChatGPT 处理依赖项来解决这个问题,但我只遇到了更多需要修复的错误,而且这个错误已经花了一段时间了。一旦我尝试运行该应用程序,它就会崩溃。如果有人知道如何解决这个问题,我将非常感激。
数据库屏幕
@Composable fun DatabaseScreen( navController: NavController, sliderValue: Float, userRepository: UserRepository ) { var userCount by remember { mutableStateOf(0) } var resultText by remember { mutableStateOf("") }
Column(
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Button(
onClick = {
CoroutineScope(Dispatchers.IO).launch {
val startTime = System.nanoTime()
for (i in 0 until (sliderValue * sliderValue * 10).toInt()) {
val age = i % 17 + 1
userRepository.insertUser(User(age = age))
}
val endTime = System.nanoTime()
val duration = endTime - startTime
// Update UI on the main thread
withContext(Dispatchers.Main) {
resultText = "Added users: ${(sliderValue * sliderValue * 10).toInt()} in $duration nanoseconds"
}
}
}
}
数据库类和函数
@Entity(tableName = "user")
data class User(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val age: Int
)
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
@Dao
interface UserDao {
@Insert
suspend fun insertUser(user: User)
@Query("SELECT * FROM user")
suspend fun getAllUsers(): List<User>
@Query("DELETE FROM user")
suspend fun clearDatabase()
}
class UserRepository(private val userDao: UserDao) {
suspend fun insertUser(user: User) {
userDao.insertUser(user)
}
suspend fun getAllUsers(): List<User> {
return userDao.getAllUsers()
}
suspend fun clearDatabase() {
userDao.clearDatabase()
}
}
主要活动
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val database = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java,
"my_database"
).build()
val userRepository = UserRepository(database.userDao())
setContent {
var navController = rememberNavController()
NavHost(navController = navController, startDestination = "mainScreen") {
composable("mainScreen") { MyApp(navController) }
composable("Screen0") {
UIScreen(navController, 5f)
}
composable("Screen1") {
AnimationScreen(navController, 5f)
}
composable("Screen2") {
ArithmeticLogicalScreen(navController, 4f)
}
composable("Screen3") {
DatabaseScreen(navController, 5f,userRepository)
}
composable("Screen4") {
FeaturesScreen(navController, 5f)
}
}
}
}
LOGCAT
致命异常:主要 进程:com.example.jurajappjetpack,PID:9583 java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.jurajappjetpack/com.example.jurajappjetpack.MainActivity}:java.lang.RuntimeException:找不到 com.example.jurajappjetpack.MainActivity.AppDatabase 的实现。 MainActivity_AppDatabase_Impl 不存在 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 在 android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 在 android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 在 android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:193) 在 android.app.ActivityThread.main(ActivityThread.java:6669) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 引起原因:java.lang.RuntimeException:找不到 com.example.jurajappjetpack.MainActivity.AppDatabase 的实现。 MainActivity_AppDatabase_Impl 不存在 在 androidx.room.Room.getGenerateImplementation(Room.kt:58) 在 androidx.room.RoomDatabase$Builder.build(RoomDatabase.kt:1357) 在 com.example.jurajappjetpack.MainActivity.onCreate(MainActivity.kt:125) 在 android.app.Activity.performCreate(Activity.java:7136) 在 android.app.Activity.performCreate(Activity.java:7127) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 在 android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 在 android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 在 android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:193) 在 android.app.ActivityThread.main(ActivityThread.java:6669) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
BUILD.GRADLE 项目级别
plugins { id("com.android.application") version "8.1.1" apply false
id("org.jetbrains.kotlin.android") version "1.8.10" apply false }
BUILD.GRADLE 模块级别
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.example.jurajappjetpack"
compileSdk = 33
defaultConfig {
applicationId = "com.example.jurajappjetpack"
minSdk = 28
targetSdk = 33
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary = true
}
}
buildTypes {
release {
isMinifyEnabled = 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"
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = "1.4.3"
}
packaging {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
}
dependencies {
implementation("androidx.core:core-ktx:1.9.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.1")
implementation("androidx.activity:activity-compose:1.7.0")
implementation(platform("androidx.compose:compose-bom:2023.03.00"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.ui:ui-tooling-preview")
implementation("androidx.compose.material3:material3")
implementation("com.google.android.material:material:1.9.0")
implementation("androidx.room:room-ktx:2.5.2")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
androidTestImplementation(platform("androidx.compose:compose-bom:2023.03.00"))
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-tooling")
debugImplementation("androidx.compose.ui:ui-test-manifest")
implementation ("androidx.navigation:navigation-compose:2.4.0")
implementation("androidx.compose.animation:animation-core")
implementation ("com.google.android.gms:play-services-location:18.0.0")
implementation ("androidx.activity:activity-ktx:1.3.1")
implementation ("androidx.fragment:fragment-ktx:1.4.0")
implementation ("androidx.lifecycle:lifecycle-runtime-ktx:2.4.0")
implementation ("androidx.camera:camera-camera2:1.1.0-beta01")
implementation ("androidx.camera:camera-lifecycle:1.1.0-beta01")
implementation ("androidx.room:room-runtime:2.5.2")
annotationProcessor ("androidx.room:room-compiler:2.5.2")
}
首先将 kapt 插件添加到模块构建 gradle 中,例如(对于所有 3 个插件):-
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt'
}
然后将
annotationProcessor ("androidx.room:room-compiler:2.5.2")
更改为
kapt 'androidx.room:room-compiler:2.5.2'
annotationProcessor 用于处理 java kapt 或 ksp 用于 Kotlin。正是处理器生成了 Java 代码,因此代码不存在。