为什么我暗恋“ lateinit属性注入器尚未初始化”?

时间:2019-05-14 08:32:29

标签: android kotlin dagger-2

学习匕首2,由向导进行。

我在我的应用程序(扩展应用程序)上创建了injector

class App : Application() {
    lateinit var injector: ApplicationComponent

    override fun onCreate() {
        super.onCreate()

        injector = DaggerApplicationComponent
            .builder()
            .applicationModule(ApplicationModule(getInstance()))
            .build()

        if (BuildConfig.DEBUG) {
            Timber.plant(Timber.DebugTree())
        }

        JodaTimeAndroid.init(this)
    }

    companion object {

        private var instance: App? = null

        fun getInstance(): App {
            if (instance == null) {
                instance = App()
            }
            return instance as App
        }
    }
}

在那之后,我写了活动:

@Inject
lateinit var mainPresenter: MainPresenter

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        sharedViewModel = ViewModelProviders.of(this).get(SharedViewModel::class.java)
        App.getInstance().injector.inject(this)
        mainPresenter.init(this)
        mainPresenter.getData()
    }

然后压碎。我怎么了?

ApplicationComponent:

@Singleton
@Component(modules = [ApplicationModule::class])
interface ApplicationComponent {

    fun inject(mainActivity: MainActivity)

    val db: TestDatabase
}

我的applicationModule很大,我想在学习的同时在一个模块上做很多事情。在这里:

@Module
class ApplicationModule(private val app: App) {

    private var db: EmployeeDatabase = Room
        .databaseBuilder(
            app,
            TestDatabase::class.java,
            TestDatabase.DATABASE_NAME.plus(".db")
        )
        .fallbackToDestructiveMigration()
        .allowMainThreadQueries()
        .build()


    @Provides
    @Singleton
    fun provideApplication(): App {
        return app
    }

    @Provides
    @Singleton
    fun provideMainViewPresenter(): MainPresenter = MainPresenter(db)

    @Singleton
    @Provides
    internal fun providesRoomDatabase(): EmployeeDatabase {
        return db
    }
}

MainPresenter:

class MainPresenter @Inject constructor(private var db: TestDatabase) {

    private var mainActivity: MainView? = null
    private val apiService = ApiService.create()

    fun init(mainView: MainView) {
        mainActivity = mainView
    }

    fun getData() {
        ...some database logic
    }

    fun onDestroy() {
        mainActivity = null
    }
}

1 个答案:

答案 0 :(得分:0)

override fun onCreate() {
    super.onCreate()
    instance = this

另外,您也应该仅用getInstance()来代替instance!!,因为您不应该尝试创建自己的App实例。