Search code examples
androidroboguice

RoboGuice @Inject annotation works, but getInjector(this).getInstance() throws ConfigurationException


On an Activity that derives from RoboActivity, I am able to add a member with an @Inject annotation that is populated after the call to super.onCreate() inside onCreate(); however, if I remove that field and attempt to retrieve the same type object from within a method, RoboGuice throws a ConfigurationException.

Example code that works:

public class MyActivity extends RoboActivity { 
    @Inject private MyType instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // instance is set 
    }   
}

However, this example does not work:

public class MyActivity extends RoboActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        doStuffThatCalls_getMyType_Eventually();
    }

    protected MyType getMyType() {
        // Exception thrown here
        return RoboGuice
                .getInjector(this)
                .getInstance(MyType.class);
    }
}

Furthermore, if I add the field, then I am able to use getInstance() as before:

public class MyActivity extends RoboActivity {

    @Inject
    private MyType instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        doStuffThatCalls_getMyType_Eventually();
    }

    protected MyType getMyType() {
        // This now works (of course, returns different instance of 'MyType')
        return RoboGuice
                .getInjector(this)
                .getInstance(MyType.class);
    }
}

I need to use the second example so that deriving classes can return a different instance of MyType, and don't want to leave the field as it may be wrongly used in the future.

How can I use RoboGuice like this?


Solution

  • When a class is never injected via an annotation, RoboGuice considers the class to be not bound and ignores the binding.
    To force the binding you need to use superbind instead of simple bind in your module:

    public class MyModule extends AbstractModule {
        @Override
        protected void configure() {
            superbind(MyType.class).to(MyTypeImpl.class);
        }
    }
    

    Source: RoboBlender wiki