Question

In my Android app project, I am using RoboGuice .

In my project, I have a singleton Class A:

@ContextSingleton
public class A{
   …
   public void method1(){…}
}

Then, I have another class B which needs an instance of A, so, in RoboGuice way, I normally declare the instance of A inside class B with injection :

public class B {
  @Inject private A a ;

   public void action(){
        a.method1(); // call method1() of class A's instance
   }
}

Sometimes, I got NullPointerException for the instance of A declared in class B. I just want to verify one concept of RoboGuice:

Is it so that in order to inject an instance of a custom class (e.g. class A) in class B, the class B has to be either injected in RoboActivity or be injected into another class (e.g. Class C) which has injected in RoboActivity?

Was it helpful?

Solution

You probably instantiate B somewhere yourself (new B()) and then you need to call the Injector manually.

When RoboGuice creates the instance B it will automatically inject the dependency A, but when you create B yourself, RoboGuice wil not know about it and you have to call the inject code yourself. This can be done by calling:

RoboInjector injector = RoboGuice.getInjector(context);
injector.injectMembersWithoutViews(yourObjectB);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top