使用最新版本的 Dagger 2,
implementation 'com.google.dagger:dagger:2.51.1'
annotationProcessor 'com.google.dagger:dagger-compiler:2.51.1'
kapt "com.google.dagger:dagger-compiler:2.51.1"
我无法使用 Dagger 2 从 Activity 注入对象,依赖注入组件和模块是用 Kotlin 编写的。
public class MainActivity extends BaseActivity {
@Inject permissionHelper permissionHelper;
@Inject MbAppFeature mpAppFeature;
@Inject SharedPref sharedPref;
@Inject ViewMvcFactory viewMvcFactory;
@SuppressLint({"ResourceType", "SuspiciousIndentation"})
@Override
protected void onCreate(Bundle savedInstanceState) {
getInjector().inject(this);
super.onCreate(savedInstanceState);
scanModeNumber = sharedPref.read("scanModeNumber",0);
isFirstRun = sharedPref.read("isFirstRun", true);
}
kotlin 代码中的基本 Activity
open class BaseActivity: AppCompatActivity() {
private val appCompositionRoot get() = (application as CustomApplication).appComponent
val activityComponent by lazy {
DaggerActivityComponent.builder()
.activityModule(ActivityModule(this, appCompositionRoot))
.build()
}
private val controllerComponent by lazy {
DaggerControllerComponent.builder()
.controllerModule(ControllerModule(activityComponent))
.build()
}
public val injector get() = controllerComponent
}
kotlin 代码中的组件
@Component(modules = [ControllerModule::class])
interface ControllerComponent {
fun inject(activity: MainActivity)
}
@Module
class ControllerModule
(private val activityComponent: ActivityComponent)
{
@Provides
fun activity() = activityComponent.activity()
@Provides
fun layoutInflater()
= activityComponent.layoutInflater()
@Provides
fun sharedPref() = activityComponent.sharedPref()
错误日志
引起:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.Integer SharedPref.read(java.lang.String, int)” 在(MainActivity.java:147)
我可以在 Dagger 控制器组件中看到注入方法是空的,有什么建议如何解决这个问题:
@Override
public void inject(ReadIDActivity activity) {
}
@Override
public void inject(ResultsIDActivity activity) {
}
@Override
public void inject(CertificateHandling activity) {
}
@Override
public void inject(MainActivity activity) {
}
@Override
public void inject(LaunchCheckFragment LaunchCheckFragment) {
}
要在您的活动中启用成员注入,请使用 @AndroidEntryPoint 注释您的类