繁体   English   中英

使用 Dagger 2 注入 Androidx Activity

[英]Injecting Androidx Activity with Dagger 2

我是在 Android 中使用 Dagger 进行依赖注入的新手

我有这个错误Unable to start activity ComponentInfo{MainActivity}: kotlin.UninitializedPropertyAccessException: lateinit property dispatchingAndroidInjector has not been initialized

我不知道我的代码中的确切错误是什么,我应该改变什么吗? 尽管在我从事的另一个项目中,除了AndroidInjection.inject(this)之外,它们具有相同的代码,并且代码运行良好

非常感谢你的帮助

这是我的文件:

应用组件

@Singleton
@Component(
modules = [AndroidSupportInjectionModule::class,
    AppModule::class, NetworkModule::class,
    ActivityBuilder::class]
)
interface AppComponent : AndroidInjector<Application> {

@Component.Builder
interface Builder {
    @BindsInstance
    fun application(application: Application): Builder

    fun build(): AppComponent
}

}

应用模块

@Module(includes = [ViewModelModule::class])

类 AppModule {

@Provides
fun provideContext(application: MyApplication): Context {
    return application.applicationContext
}

@Provides
fun provideHandler(): Handler {
    return Handler()
}

@Provides
@Singleton
fun provideSharedPreferences(context: Context): SharedPreferences {
    return context.getSharedPreferences("prefs", Context.MODE_PRIVATE)
}

@Provides
@Singleton
fun provideSharedPreferenceUtils(context: Context): SharedPreferenceUtils {
    return SharedPreferenceUtils(provideSharedPreferences(context))
}

}

活动生成器

@Module
abstract class ActivityBuilder {

@ContributesAndroidInjector
abstract fun bindMainActivity(): MainActivity

}

网络模块

@Module(includes = [AppModule::class])
// Safe here as we are dealing with a Dagger 2 module
@Suppress("unused")
class NetworkModule {

@Provides
@Singleton
fun provideCache(context: Context): Cache {
    return Cache(context.cacheDir, CACHE_SIZE)
}

@Provides
@Singleton
fun provideOkHttpClient(cache: Cache, context: Context): OkHttpClient {
    return OkHttpClient.Builder()
            .cache(cache)
            .addInterceptor { chain ->
                var request = chain.request()
                request = if (hasNetwork(context)!!)
                    request.newBuilder().header("Cache-Control", "public, max-age=" + 5).build()
                else
                    request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build()
                chain.proceed(request)
            }
            .build()
}

/**
 * Provides the Quotes service implementation.
 * @param retrofit the Retrofit object used to instantiate the service
 * @return the Quote service implementation.
 */
@Provides
@Singleton
fun provideQuotesAPI(retrofit: Retrofit): QuotesAPI {
    return retrofit.create(QuotesAPI::class.java)
}

/**
 * Provides the Retrofit object.
 * @return the Retrofit object
 */
@Provides
@Singleton
fun provideRetrofitInterface(okHttpClient: OkHttpClient): Retrofit {
    return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(MoshiConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
            .client(okHttpClient)
            .build()
}

}

视图模型模块

@Module
abstract class ViewModelModule {

@Binds
abstract fun bindViewModelFactory(factory: MyViewModelFactory): ViewModelProvider.Factory

@Binds
@IntoMap
@ViewModelKey(QuotesListViewModel::class)
internal abstract fun bindsQuotesListViewModel(quotesListViewModel: QuotesListViewModel): ViewModel

@Binds
@IntoMap
@ViewModelKey(QuoteListItemViewModel::class)
internal abstract fun bindsQuoteListItemViewModel(quoteListItemViewModel: QuoteListItemViewModel): ViewModel

}

我的应用程序

class MyApplication : Application(), HasActivityInjector {

@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity>

override fun activityInjector(): AndroidInjector<Activity> = dispatchingAndroidInjector

override fun onCreate() {
    super.onCreate()
    // StateSaver.setEnabledForAllActivitiesAndSupportFragments(this, true)

    // initialise dependency injection
    DaggerAppComponent
        .builder()
        .application(this)
        .build()
        .inject(this)

}

override fun attachBaseContext(base: Context) {
    super.attachBaseContext(base)
    MultiDex.install(this)
}

}

主要活动

class MainActivity : DaggerAppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

private lateinit var binding: ActivityMainBinding
private lateinit var menu: Menu

override fun onCreate(savedInstanceState: Bundle?) {
    AndroidInjection.inject(this)
    super.onCreate(savedInstanceState)
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
}
}

最后,经过多次尝试,我发现了我的错误,在AppComponent 中我应该调用MyApplication类而不是Application

@Singleton
@Component(
modules = [AndroidSupportInjectionModule::class,
AppModule::class, NetworkModule::class,
ActivityBuilder::class]
)
interface AppComponent : AndroidInjector<MyApplication> {

@Component.Builder
interface Builder {
@BindsInstance
fun application(application: MyApplication): Builder

fun build(): AppComponent
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM