【发布时间】:2020-01-14 02:43:50
【问题描述】:
我创建了一个自定义 DaggerApplication 类并为其编写了足够的 AppModule 和 AppComponent 类,但是在访问我的 injected 上下文的内容解析器时出现空指针异常。 (这是我的全球应用程序上下文)。我试图将我的问题缩小为以下代码行中的一个小示例。
这是我的应用程序类:
class CustomPlayerApplication @Inject constructor() : DaggerApplication() {
companion object{
@SuppressLint("StaticFieldLeak")
lateinit var context: Context
}
override fun onCreate() {
super.onCreate()
context = this
}
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerAppComponent.builder().create(this).build()
}
}
这是我的 AppModule:
@Module
class AppModule {
@Provides
@Singleton
fun providesLibraryManager(application: CustomPlayerApplication): LibraryManager {
return LibraryManager(application).apply{
createContentResolver()
}
}
}
这是我的应用组件:
@Singleton
@Component(
modules = [
AndroidSupportInjectionModule::class,
AppModule::class
]
)
interface AppComponent : AndroidInjector<CustomPlayerApplication> {
@Component.Builder
interface Builder {
@BindsInstance
fun create(app: Application): Builder
fun build(): AppComponent
}
fun libraryManager(): LibraryManager
}
这是我的 libraryManager 类。
class LibraryManager @Inject constructor(private val context: Context) {
fun createContentResolver(): ContentResolver? {
return context.contentResolver
}
}
在调用 contentResolver 时,应用程序崩溃并出现空指针异常,说明我无法在空对象上调用 contentResolver。在调试时,我发现这里的上下文不为空,但我也不能调用它的 contentResolver。
我确信在将我的课程更改为 DaggerApplication 并使用 2.24 之前,我的代码可以正常工作。无论发生什么,都可能是因为 @bindInstance 注释,但我找不到任何相关问题。
编辑:为了进一步解释我的问题,虽然在“AppModule, the app crashes because thecontext.ContentResolver”中调用了提供方法,但在空对象引用上调用,而上下文不为空,它实际上是我的应用程序上下文。我有点困惑,实际问题可能是什么。
【问题讨论】:
-
@Ashish 阅读你放在这里的链接,我的问题根本不相似。并非所有
null pointer exceptions都必须来自类似问题!这是由于我实现注入类的方式不一致造成的。 -
如果您遇到异常,请始终在您的问题中包含堆栈跟踪
标签: android kotlin dependency-injection dagger-2 dagger