0

I am using Dagger and so far its good. I have one module for all the Views (Activities and fragments), and I am injecting them through Object graph. Now I want to include Custom view and my Module looks something like this

@Module(
injects = {
    //Activity
    MainActivity.class,


    //Fragments
    LookupSearchResultsFragment.class,


    // Views

    MainSearchComponent.class
},
//includes = {
//    PersistenceModule.class
//},
library = true,
complete = false,
addsTo = AndroidModule.class)

In my MainSearchComponent how should I inject Object Graph? I am currently doing this:

ObjectGraph.create((BaseActivity)getContext()).inject(this);

But I get this error. Caused by: java.lang.IllegalStateException: Module adapter for class ...MainActivity could not be loaded. Please ensure that code generation was run for this module.

SoH
  • 2,180
  • 2
  • 24
  • 53

2 Answers2

1

Firstly, you should pass @Module-annotated classes to ObjectGraph.create(), not Activity classes. Secondly, you should not create graph every single time you need to inject() something. The common practice is to make objectGraph a field of your Application class. That's what you can get:

// Application class
objectGraph = ObjectGraph.create(new AndroidModule());

Then in your Activity's onCreate():

@Override public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  MyApp app = (MyApp) getApplication();
  activityGraph = app.getObjectGraph().plus(new ActivityModule());
  activityGraph.inject(this); // inject with respect of activity-specific components
}

And don't forget to clear strong ref to local graph to GC it ASAP:

@Override public void onDestroy() {
  activityGraph = null;
  super.onDestroy();
}
colriot
  • 1,978
  • 1
  • 14
  • 21
  • what if I want to inject a class with run time variables? It wont help me to inject everything in Application class then would it? – SoH Jan 19 '15 at 09:24
  • @SoH What do you mean by runtime vars? Can you give an example? – colriot Jan 20 '15 at 14:51
  • I have class A which injects another class B based on the variables it receives from the calling class C. Is it doable? – SoH Jan 20 '15 at 15:08
  • @SoH you can implement `@Provides B provideB(C c)` and `@Provides C provideC()` methods in one of your modules. Then based on the `C` value provided into first method by the second method, you can decide what particular `B` instance to provide. Of course, in `A` you will mark `B` instance with `@Inject`. Is it what you wanted? – colriot Jan 20 '15 at 15:22
0

ok so I found the solution. I needed to inject the module where I have specified my component. So for me I had to write the following instead of

ObjectGraph.create((BaseActivity)getContext()).inject(this);

This got it working.

ObjectGraph.create(new AcitivityModule()).inject(this);
SoH
  • 2,180
  • 2
  • 24
  • 53