【发布时间】:2016-03-09 23:10:04
【问题描述】:
我在基于 LibGDX 的游戏中注入一些依赖项时遇到问题。 谁能指出我缺少什么?
我有两个模块。
首先提供Android的Context:
@Module
public class AppModule {
Context context;
public AppModule(Context context) {
this.context = context;
}
@Provides
@Singleton
Context providesContext() {
return context;
}
}
第二个提供与 Google Analytics 交互的类:
@Module
public class ServicesModule {
@Provides
@Singleton
AnalyticsUtils providesAnalyticsUtils(Context context) {
return new AnalyticsUtils(context);
}
}
我的组件类是这样实现的:
@Singleton
@Component(modules = {AppModule.class, ServicesModule.class})
public interface GameComponent {
void inject(Launcher launcher);
}
现在,我添加了自定义应用程序类(在清单中定义),并在其中实例化了我的组件:
public class GameApplication extends Application {
private GameComponent gameComponent;
@Override
public void onCreate() {
super.onCreate();
gameComponent = DaggerGameComponent.builder()
.appModule(new AppModule(this))
.servicesModule(new ServicesModule())
.build();
}
public GameComponent getGameComponent() {
return gameComponent;
}
}
在 LibGDX Android 的启动器中,在onCreate 方法中我调用组件的inject() 方法:
public class Launcher extends AndroidApplication {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((GameApplication) getApplication()).getGameComponent().inject(this);
initialize(new GameName());
}
}
假设GameName 是一个扩展LibGDX 的Game 类的类。在 create 方法中,我正在调用 setScreen 方法来启动我的菜单屏幕。
我的MenuScreen 班级:
public class MenuScreen extends ScreenAdapter {
@Inject AnalyticsUtils analyticsUtils;
public MenuScreen(GameName game) {
// Some initialization.
useAnalytics();
}
private void useAnalytics() {
analyticsUtils.someMethod();
}
}
如上所述,在MenuScreen 类中,我想使用字段注入来注入AnalyticsUtils 类。
在构造函数中,我正在调用一个使用analyticsUtils 对象的方法并调用它的方法。
在我正在呼叫analyticsUtils.someMethod() 的线路上,我得到了NullPointerExcetion(试图在null 对象上呼叫.someMethod())。
我应该在注入任何东西的每个类中使用组件的inject() 方法(无论使用字段/构造函数注入)吗?
我阅读了很多 Dagger 的教程和文档,但是每个可用的示例都很简单(大多数情况下,它们显示了活动中的简单注入)。
经过几个小时的尝试,我决定我需要请教在 Dagger 方面更有经验的人。我会很高兴任何提示和/或资源。
【问题讨论】:
标签: java android dependency-injection libgdx dagger-2