0

我收到lateinit错误,但我没有看到问题

 kotlin.UninitializedPropertyAccessException: lateinit property soldatDatabase has not been initialized
        at pl.rybson.soldatlobby.di.RoomModule.provideServersDao(RoomModule.kt:37)
        at pl.rybson.soldatlobby.di.RoomModule_ProvideServersDaoFactory.provideServersDao(RoomModule_ProvideServersDaoFactory.java:27)
        at pl.rybson.soldatlobby.DaggerBaseApplication_HiltComponents_ApplicationC.getServersDao(DaggerBaseApplication_HiltComponents_ApplicationC.java:113)
        at pl.rybson.soldatlobby.DaggerBaseApplication_HiltComponents_ApplicationC.getMainRepository(DaggerBaseApplication_HiltComponents_ApplicationC.java:127)
        at pl.rybson.soldatlobby.DaggerBaseApplication_HiltComponents_ApplicationC.access$1800(DaggerBaseApplication_HiltComponents_ApplicationC.java:53)
        at pl.rybson.soldatlobby.DaggerBaseApplication_HiltComponents_ApplicationC$SwitchingProvider.get(DaggerBaseApplication_HiltComponents_ApplicationC.java:431)
        at pl.rybson.soldatlobby.ui.home.HomeViewModel_AssistedFactory.create(HomeViewModel_AssistedFactory.java:24)
        at pl.rybson.soldatlobby.ui.home.HomeViewModel_AssistedFactory.create(HomeViewModel_AssistedFactory.java:12)

和 Module.kt

@Module
@InstallIn(ApplicationComponent::class)
object RoomModule {

    private lateinit var soldatDatabase: SoldatDatabase

    @Singleton
    @Provides
    fun provideRoom(@ApplicationContext context: Context): SoldatDatabase {
        soldatDatabase = Room.databaseBuilder(
            context,
            SoldatDatabase::class.java,
            "soldat.db"
        )
            .build()
        return soldatDatabase
    }


    @Singleton
    @Provides
    fun provideServersDao(): ServersDao {
        return soldatDatabase.serversDao()
    }

}
4

1 回答 1

1

Dagger 仅在需要时创建依赖项。由于provideServersDao不接受任何参数,Dagger 得出结论,ServersDao可以在没有任何依赖项的情况下提供,并且没有理由调用provideRoom.

由于ServersDao实际上依赖于 的实例SoldatDatabase,因此您应该要求 Dagger 为您提供一个:

@Module
@InstallIn(ApplicationComponent::class)
object RoomModule {

    @Singleton
    @Provides
    fun provideRoom(@ApplicationContext context: Context): SoldatDatabase {
        return Room.databaseBuilder(
            context,
            SoldatDatabase::class.java,
            "soldat.db"
        )
            .build()
    }


    @Singleton
    @Provides
    fun provideServersDao(soldatDatabase: SoldatDatabase): ServersDao {
        return soldatDatabase.serversDao()
    }

}
于 2020-08-12T22:26:32.483 回答