我是Otto的新手,我在与Dagger依赖注入器和JobManager一起完成其功能时遇到了严重的麻烦。每当我启动我的应用程序时,我都会收到相同的错误消息:
"java.lang.RuntimeException: Unable to resume activity {sdos.juanjosemelero.pruebaormlite2/sdos.juanjosemelero.pruebaormlite2.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.squareup.otto.Bus.register(java.lang.Object)' on a null object reference"
[...]
"Caused by java.lang.NullPointerException:
Attempt to invoke virtual method 'void com.squareup.otto.Bus.register(java.lang.Object)' on a null object reference".
它引用的行就是这一行:
bus.register(this);
这是我的活动:
public class MainActivity extends ActionBarActivity {
@Inject Bus bus;
@Override
protected void onResume() {
super.onResume();
bus.register(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
bus.unregister(this);
}
}
这是我的匕首注射模块:
@Module(
injects = {MainActivity.class},
library = true
)
public class MyModule {
private final MyApplication application;
public MyModule (MyApplication application) {
this.application = application;
}
@Provides
@Singleton
MyApplication provideMyApplication() {
return application;
}
@Provides
@Singleton
public Bus provideBus (){
return new Bus(ThreadEnforcer.ANY);
}
}
MyApplication类,以防它看起来很有意思:
public class MyApplication extends Application {
private ObjectGraph objectGraph;
private static MyApplication application;
//Constructor
public MyApplication() {
application = this;
}
@Override
public void onCreate() {
super.onCreate();
buildObjectGraph();
}
public void buildObjectGraph() {
objectGraph = ObjectGraph.create(new MyModule(this));
}
public void inject(Object o) {
objectGraph.inject(o);
}
public static MyApplication get() {
return application;
}
}
我想以某种方式初始化MainActivity吗?
答案 0 :(得分:5)
您没有使用对象图在onCreate中注入MainActivity。就这样。
致电
MyApplication.get().inject(this);
在MainActivity onCreate()。