我有一个Android应用程序,我正在尝试使用匕首。我决定使用全局图+活动图。我有三个模块:
AndroidModule
@Module(library = true)
public class AndroidModule {
private final MApplication mApplication;
public AndroidModule(MyApplication application) {
mApplication = application;
}
@Provides @Singleton @ForApplication Context provideApplicationContext() {
return mApplication;
}
}
MyAppModules
@Module(
injects = {
MainActivity.class,
AddFragment.class,
AddMapFragment.class,
MyActivity.class,
ListFragment.class,
MyMapFragment.class,
RetainFragment.class,
SingleActivity.class,
UserActivity.class,
UserLoginFragment.class,
UserProfileActivity.class,
UserProfileFragment.class,
UserRegisterFragment.class,
WelcomeFragment.class
},
complete = false,
library = true,
includes = ActivityModule.class
)
public class MyAppModule {
private final Bus mBus = new Bus();
@Provides @Singleton Bus provideBus() {
return mBus;
}
@Provides @Singleton
RequestQueue provideRequestQueue(@ForApplication Context context) {
return Volley.newRequestQueue(context);
}
@Provides @Singleton Api provideApi(RequestQueue queue) {
return new AppApi(queue);
}
@Provides Logger provideLogger() {
return new MyLogger();
}
}
ActivityModule
@Module(
complete = false,
library = true
)
public class ActivityModule {
private BaseActivity mActivity;
public ActivityModule() {}
public ActivityModule(BaseActivity activity) {
mActivity = activity;
}
@Provides @Singleton @ForActivity Context provideActivityContext() {
return mActivity;
}
@Provides @Singleton LocationClientFactory provideLocationClientFactory() {
return new LocationClientFactory(mActivity);
}
}
我必须在MyAppModule
上使用包含ActivityModule
,但没有它,应用程序崩溃说它可以在Context
上找到构造函数并且无法注入Activity
} Context
。
图表配置正确吗?我将模块添加到Application
和BaseActivity
中的图表中,我认为这已经足够了,我不需要包含,但我不确定我是否完全理解配置这个过程。
修改
像这样,dagger没有错误但是如果我尝试注入Activity
Context
,则在运行时它是null
。
答案 0 :(得分:4)
如果有人有兴趣,解决方案就是删除
injects = {
MainActivity.class,
AddFragment.class,
AddMapFragment.class,
MyActivity.class,
ListFragment.class,
MyMapFragment.class,
RetainFragment.class,
SingleActivity.class,
UserActivity.class,
UserLoginFragment.class,
UserProfileActivity.class,
UserProfileFragment.class,
UserRegisterFragment.class,
WelcomeFragment.class
}
从MyAppModule 并将其放在ActivityModule中。