Goofyahead
Goofyahead

Reputation: 5884

Injecting on adapters with dagger in android

I'm just trying dagger instead of roboguice, so far butterknife was awesome and simple, point for it :)

But dagger on the other hand I found it less configurable than roboguice, I have to benchmark if its worth the change but in this case I'm looking on how to inject stuff in lets say Adapters, this is what I made and it works:

public class PeopleAdapter extends BaseAdapter {

private static final String TAG = PeopleAdapter.class.getName();
@Inject
TempoSharedPreferences prefs;

private LinkedList<People> elements;

public PeopleAdapter (LinkedList<People> elements, TempoApplication app) {
    this.elements = elements;
    app.inject(this);
    Log.d(TAG, "registered: " + prefs.isRegistered());
} ....

But on the Activity that creates this instance I have to get an Application that allows to inject, also I have to add to the module every time the classes that use that dependency, roboguice did all that for me and had only one entry point where to modify the stuff.

I'm I doing something wrong? is there any better way to perform this injections? Avoid the declaration of each class on the module?

@Module(injects = {
    MainActivity.class,
    PeopleAdapter.class
    },
    library = true)
public class AndroidModule { ....

I'll appreciate any comment or best practice or experience on this.

Thanks!

Upvotes: 6

Views: 3243

Answers (1)

tomrozb
tomrozb

Reputation: 26281

You're doing everything right. Dagger needs some more configuration than Roboguice, but is also more powerful (configurable). Did you try scoped graphs or lazy injection already?

Every single class that uses injection must be listed in the injects param of the module. There's no way to avoid declaration of each class.

Upvotes: 2

Related Questions