Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException with Otto and Dagger

I'm new to Otto and I'm having serious trouble making out its functioning together with Dagger dependency injector and JobManager. Whenever I launch my application, I keep getting the same error message:

"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".

The line it reffers is this one:

bus.register(this);

This is my activity:

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);
    }
}

And here is my Module for Dagger injection:

@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);
    }
}

And MyApplication class in case it is interesting to take a look at it:

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;
    }
}

Am I suppose to initialize MainActivity somehow?

like image 886
Juan José Melero Gómez Avatar asked Mar 24 '15 07:03

Juan José Melero Gómez


1 Answers

You're not injecting the MainActivity in onCreate with the object graph. That's all.

Just call

MyApplication.get().inject(this);

in MainActivity onCreate().

like image 62
EpicPandaForce Avatar answered Nov 15 '22 04:11

EpicPandaForce