James King
James King

Reputation: 2445

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

Upvotes: 1

Views: 3001

Answers (2)

shekar
shekar

Reputation: 1271

This can also be done by Constructor injection

public class Analytics {

    @Inject
    public Analytics(PageMap pagesByActivity, HitFactory hitFactory,
                                    Provider<String> storeIdProvider,
                                    Provider<Checker> checkerProvider,
                                    String suiteIds,
                                    DeviceInfo deviceInfo) {

            this.deviceInfo = deviceInfo;
    }
}

If you want to inject in the class where we don't have Constructor like BroadcastReceiver then do the following.

public class Receiver extends BroadcastReceiver {
    @Inject
    AlarmReceiver alarm;

    @Override
    public void onReceive(Context context, Intent intent) {
      ((AppApplication)context.getApplicationContext()).getComponent().inject(this);
      alarm.setAlarm(context);
    }
}

add in AppComponent

void inject(BootReceiver receiver);

Upvotes: 2

Clark Wilson
Clark Wilson

Reputation: 389

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:

@Provides
DeviceInfo provideDeviceInfo(){
    return new DeviceInfo();
}

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

Upvotes: 2

Related Questions