gpt4 book ai didi

java - 如果没有 @Provides- 或 @Produces-annotated 方法,则无法提供 Dagger 2 Activity

转载 作者:行者123 更新时间:2023-11-30 00:10:08 30 4
gpt4 key购买 nike

我是 Dagger 的新手,我正在尝试实现一个继承自进行注入(inject)的类的类。当我在 MainActivity 中取出一个组件的注入(inject)并从 BaseActivity 继承它时,事情就崩溃了。

我的应用组件类:

@Singleton
@Component(modules = {NetworkModule.class, ApplicationModule.class,
AndroidModule.class})
public interface AppComponent {

void inject (BaseActivity baseActivity);
void inject (MainActivity mainActivity);
}
}

我的 ActivityModule 类:

@Module
public class ActivityModule {

private Activity activity;

public ActivityModule(Activity activity) {
this.activity = activity;
}

@PerActivity
@Provides
@ActivityContext
public Context provideContext() {
return activity;
}
}

我的 ApplicationModule 类:

@Module
public class ApplicationModule {

private Application application;

public ApplicationModule(Application application) {
this.application = application;
}

@Provides
@Singleton
@ApplicationContext
public Context provideContext() {
return this.application;
}

@Provides
@Singleton
public FCMTokenHelper provideFCMTokenHelper(Context context, ApiService apiService) {
UserRepoImpl userRepo = new UserRepoImpl(apiService);
return new FCMTokenHelper(context, context.getClass().getSimpleName(), userRepo);
}

@Provides
@Singleton
public UserRepoContract providerUserRepo(ApiService apiService) {
return new UserRepoImpl(apiService);
}

}

我的两个类(class)(都在 kotlin 中)

class MainActivity : BaseActivity() { 

}

abstract class BaseActivity : AppCompatActivity(), GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ActivityCompat.OnRequestPermissionsResultCallback, LocationListener {

@Inject
lateinit var userRepo: UserRepoContract

@Inject
internal var tokenHelper: FCMTokenHelper? = null
}

错误:

Error:(51, 10) error: .BaseActivity cannot be provided without an @Provides-annotated method. BaseActivity is injected at AppComponent.inject(baseActivity) Error:(75, 10) error: MainActivity cannot be provided without an @Inject constructor or from an @Provides-annotated method. MainActivity is injected at .AppComponent.inject(mainActivity)

使用 Dagger 2 版本 2.9安卓工作室 3.0Kotlin 和 Java

最佳答案

我的问题在这里:

@Inject
internal var tokenHelper: FCMTokenHelper? = null

将其更改为:

@Inject
lateinit var tokenHelper: FCMTokenHelper

修复了问题。看个好解释here.

关于java - 如果没有 @Provides- 或 @Produces-annotated 方法,则无法提供 Dagger 2 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48289126/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com