omaraflak / Dagger2-Sample

Very simple example to use Dagger 2
13 stars 12 forks source link

How to use injectable class in non Activity/Fragment class #2

Open Harmeetkaur01 opened 6 years ago

Harmeetkaur01 commented 6 years ago

Hi , I'm currently using dagger 2 in my project. I'm unable to access injectable class through @Inject in non activity/fragment class. I have a handler class and want to use injectable in that class. Can u help me how to do this.

@Singleton
@Component(modules = {
        AndroidSupportInjectionModule.class,
        ApplicationModule.class,
        ActivityBuilder.class})
public interface ApplicationComponent extends AndroidInjector<DaggerApplication> {

    void inject(AppController appController);
    void inject(APIHandler apiHandler);

    @Override
    void inject(DaggerApplication daggerApplication);

    @Component.Builder
    interface Builder{
        @BindsInstance
        Builder application(Application application);
        ApplicationComponent build();
    }
}

This is my ApplicationComponent class I added a method inject(APIHandler apiHandler) in this and tried getting @injent DataManager dataManager(injectable class) in ApiHandler class but getting it null, any other thing i need to do in APIHandler class.Let me know if i m missing something where as i m able to get it in activity and fragment

APIHandler class


public class APIHandler {

    /**
     * Activity reference object
     */
    private Activity mActivity;
    /**
     * Debug TAG
     */
    private String TAG = APIHandler.class.getSimpleName();
 @Inject
    DataManager dataManager;

    /**
     * Public Constructor for this class
     *
     * @param mActivity
     * @param webAPIResponseListener
     */
    public APIHandler(Activity mActivity, WebAPIResponseListener webAPIResponseListener) {
        this.mActivity = mActivity;
        this.mResponseListener = webAPIResponseListener;
        postAPICall();
    }
//API call
    public void postAPICall() {
//doing something
if(dataManager != null){
dataManager.setName();
}
}
omaraflak commented 6 years ago

You have to inject the generated dagger component into APIHandler into order to use @inject annotation. In APIHandler constructor you should add something like :

DaggerApplicationComponent.builder()
    .androidSupportInjectionModule(...)
    .applicationModule(...)
    .activityBuilder(...)
    .build().inject(this);