Question

I'm experimenting with Dagger and trying to get an ObjectGraph set up. I created a BaseModule that houses stuff like my SharedPreferences and Bus. I created a WidgetModule that contains things such as Picasso for image loading.

I'm trying to inject Picasso into one of my adapter classes. In the adapter constructor I get my ObjectGraph instance and then inject the adapter. I get a runtime exception complaining:

Caused by: java.lang.IllegalArgumentException: No inject registered for members/<ParentClass>$1. You must explicitly add it to the 'injects' option in one of your modules.

This is odd to me because I don't perform any injections in that class. ParentClass is where I create my adapter, but the injection happens in the adapter itself. Do I really need to declare the parent class that has no injections into my injects annotation? Here is my adapter constructor:

public MyAdapter(Context context, int textViewResourceId, List<Item> items) {
        super(context, textViewResourceId, items);
        MyApplication.get(getContext()).inject(this); //exception occurs here
}

Here are my modules:

@Module(
        injects = {
                MyApplication.class,
        }
)
public final class BaseModule {
    //...
}

@Module(
        injects = MyAdapter.class
)
public class WidgetModule {
    public WidgetModule(Application app) {
        this.app = app;
    }

    @Provides
    @Singleton
    Picasso providePicasso() {
        return new Picasso.Builder(app)
                .build();
    }
}

As you can see I have my adapter class in my injects, so why is it mentioning the parent class at all?

Also, is this the proper structure for creating an ObjectGraph? The documentation on includes and addsTo is very sparse and all of the demo projects like U2020 are ambiguous to what they actually mean. I'm trying to separate the Modules so that I can override them easily if I need to.

edit: It turns out that I get the exception even if I add the parent class to both modules. This is bizarre.

Was it helpful?

Solution

I ended up fixing this. For some reason Dagger just couldn't inject my adapter. What I did was inject Picasso into the adapter's parent (my custom View) and then pass it to my adapter via its constructor. Not sure why this works as opposed to injecting in my adapter directly because now I have a useless Picasso field in my View class. I'm still open to other answers that provide a better solution, but this works for now.

OTHER TIPS

Use

((MyApplication) context.getApplicationContext()).inject(this);

instead of

MyApplication.get(getContext()).inject(this);

and add

public void inject(Object object) { graph.inject(object); } 

in MyApplication as seen in Dagger samples.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top