gpt4 book ai didi

android.app.Application 无法转换为 LifecycleOwner

转载 作者:搜寻专家 更新时间:2023-11-01 07:41:45 25 4
gpt4 key购买 nike

不幸的是,我不能将 getApplication() 用作 LifecycleOwner,因为 android.app.Application 似乎没有实现它。

为什么 android.app.Application 没有实现 LifecycleOwner?

我尝试使用 getApplication() 作为 LiveData 的 LifecycleOwner 的代码:

result.observe(getApplication(), ....);

Gradle :

apply plugin: 'com.android.application'

android {
compileSdkVersion 28
defaultConfig {
applicationId "XXXX"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
}

}

dependencies {
// GENERAL
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0-alpha07'
implementation "androidx.room:room-runtime:2.1.0"
annotationProcessor "androidx.room:room-compiler:2.1.0"
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.0.0"
implementation "androidx.navigation:navigation-fragment:2.1.0-alpha05"
implementation "androidx.navigation:navigation-ui:2.1.0-alpha05"

// Third party libraries

// Jetbrains
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.31'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.0'

// Glide
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'

// Fotoapparat
implementation 'io.fotoapparat:fotoapparat:2.7.0'

// TEST
testImplementation 'junit:junit:4.12'

// ANDROID TEST
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation "androidx.room:room-testing:2.1.0"
}

错误:

java.lang.ClassCastException: ...
android.app.Application cannot be cast to androidx.lifecycle.LifecycleOwner

最佳答案

Why does android.app.Application not implement LifecycleOwner?

它没有生命周期。它被创建,然后在整个过程中存在。

Code where I try to use getApplication() as LifecycleOwner for LiveData:

要么使用具有实际生命周期的东西( Activity 、 fragment 等),要么使用 observeForever()

关于android.app.Application 无法转换为 LifecycleOwner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56688851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com