James King James King - 1 year ago 118
Java Question

Android - Dagger injection into a non Activity or fragment

So we use dagger 2 within our app but now I want to inject into a class which is not an activity or fragment. How can I do this. So I have the following class which I want to inject into:

public class Analytics {

private final PageMap pagesByActivity;
private final HitFactory hitFactory;
private final Provider<String> storeIdProvider;
private final Provider<StockChecker> stockCheckerProvider;
public Analytics(PageMap pagesByActivity, HitFactory hitFactory,
Provider<String> storeIdProvider,
Provider<Checker> checkerProvider,
String suiteIds) {

this.pagesByActivity = pagesByActivity;
this.hitFactory = hitFactory;
this.storeIdProvider = storeIdProvider;
this.checkerProvider = checkerProvider;

This class job is to fire off analytics. I want to infect a class called deviceInfo which i already have a provides method.

If I try and inject now, it compiles and runs, but then crashes giving me a null object

Answer Source

Add deviceInfo as a constructor parameter to the Analytics class. Then in your Dagger Module provides method, include deviceInfo in the parameter. This means that you'll need to let Dagger create your Analytics object for you. Dagger will create the DeviceInfo object first, and then create the Analytics object second. The code in your module should look something similar to below:

DeviceInfo provideDeviceInfo(){
    return new DeviceInfo();

Analytics provideAnalytics(DeviceInfo deviceInfo){
    return new Analytics(deviceInfo, [... other parameters]);