我有一个应用程序(模块+组件)
@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
void inject(App app);
Serializer getSerializer();
ListOfCallingLists getListOfCallingLists();
Context getContext();
App getApp();
}
和
@Module
public class AppModule {
private final App app;
public AppModule(App app) {
this.app = app;
}
@Provides
Serializer provideSerializer() {
return new BinarySerializer();
}
@Provides
Context provideContext() {
return app;
}
@Provides
App provideApp() {
return app;
}
}
和
@Singleton
public class ListOfCallingLists implements Serializable {
...
@Inject
public ListOfCallingLists(Context context,
Serializer serializer) {
this.serializer = serializer;
...
}
}
App
是应用程序,我在manifest中注册了它:
public class App extends Application {
private AppComponent appComponent;
public static App get(Context context) {
return (App) context.getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
if (appComponent == null)
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
appComponent.inject(this);
}
public AppComponent getComponent() {
return appComponent;
}
}
最后活动:
public class CallListsActivity extends AppCompatActivity {
@Inject
ListOfCallingLists list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
@Override
public void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// list here is null why?
}
}
答案 0 :(得分:1)
在AppComponent中,您需要添加:
void inject(CallListsActivity callListActivity);
在您的CallListsActivity onCreate()
中,您需要告诉您的CallListsActivity是如何注入的。
例如,构建您的AppComponent并注入活动,或者您可以使用新的android注入器:https://google.github.io/dagger/android.html