Android新手用Dagger2+MVVM+Kotlin遇lateinit未初始化问题求助
lateinit property activityInjector has not been initialized Error in Dagger2 + Kotlin + MVVM Setup Hey there! Let's break down why you're hitting this error and how to fix it quickly.
Root Cause
The UninitializedPropertyAccessException happens because Dagger isn't actually injecting the activityInjector and fragmentInjector fields in your PruebaDaggerApp class. Look at your AppComponent definition:
@Singleton @Component(modules = [AndroidSupportInjectionModule::class, AppModule::class, ActivityModule::class]) interface AppComponent { fun inject(app: Application) }
Your inject method accepts a base Application type, but your PruebaDaggerApp is a subclass with its own @Inject-annotated properties. Dagger only injects fields that exist on the type specified in the inject method signature—so it's ignoring the fields in your subclass.
Step-by-Step Fix
Update your AppComponent's inject method
Change the parameter type fromApplicationto your specificPruebaDaggerAppclass:@Singleton @Component(modules = [AndroidSupportInjectionModule::class, AppModule::class, ActivityModule::class]) interface AppComponent { fun inject(app: PruebaDaggerApp) }Rebuild your project
Dagger uses annotation processing to generate code, so you'll need to clean and rebuild your project for the changes to take effect. In Android Studio, go toBuild > Clean Projectfollowed byBuild > Rebuild Project.Double-check critical setup points
- Ensure your
MainActivityextendsDaggerAppCompatActivity(your error log confirms this is already the case, but it's worth verifying):class MainActivity : DaggerAppCompatActivity() { // ... your activity code } - Confirm your
PruebaDaggerAppis correctly registered inAndroidManifest.xml:<application android:name=".PruebaDaggerApp" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
- Ensure your
Why This Works
By changing the inject method to accept PruebaDaggerApp, Dagger now knows to inject all @Inject-annotated fields in that specific class, including activityInjector and fragmentInjector. When you call DaggerAppComponent.builder().build().inject(this) in your app's onCreate, Dagger will properly initialize those properties before they're accessed by the Dagger Android framework.
内容的提问来源于stack exchange,提问作者Otto Cheley

