android-dagger2-example icon indicating copy to clipboard operation
android-dagger2-example copied to clipboard

How to use injectable class in non Activity/Fragment class

Open Harmeetkaur01 opened this issue 6 years ago • 0 comments

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();
}
}

Harmeetkaur01 avatar Jun 07 '18 11:06 Harmeetkaur01