0

I'm new to hilt and dagger and I don't know if what I'm doing is wrong or if its not working for a different reason so please bear with me.

I want to inject a class that depends on another class into a view holder class.

The view holder extends BaseViewHolder, the class I want to inject into it is an image helper class which depends on glide.

I have a module that provides glide

@Module
@InstallIn(ApplicationComponent.class)
public class GlideModule {

    @Provides
    public static RequestManager provideGlideRequestManager(@ApplicationContext Context context) {
        return Glide.with(context);
    }
}

This module is used else where in my app so I know it works.

I've annotated the image helpers constructor with @Inject and I'm trying to field inject glide into this class like this

@Inject
public RequestManager glide;

@Inject
public ImageHelper() {
}

and then in my view holder I've annotated the image helper with @Inject

@Inject
public ImageHelper imageHelper;

public SentenceViewHolder(View view, ItemTouchListener onItemTouchListener, OnStartDragListener mDragStartListener) {
    super(view);
    this.v = view;
    findViewIds(onItemTouchListener, mDragStartListener);
}

inside my findViewIds method I try to access the image helper but its null,

So I tried building a module for it with no joy

@Module
@InstallIn(ActivityComponent.class)
public class ImageHelperModule {

@Singleton
@Provides
public ImageHelper provideImageHelper() {
    return new ImageHelper();
}
}

any help is appreciated

Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132
martinseal1987
  • 1,862
  • 8
  • 44
  • 77

1 Answers1

3

Simply adding @Inject annotation to a field is not enough to have Hilt provide it. You also need to define an EntryPoint (in some way).

  1. Simplify your ImageHelper (no need for field injection). Is it a Singleton?
@Singleton
class ImageHelper {
  public RequestManager glide;

  @Inject
  public ImageHelper(RequestManager glide) {
    this.glide = glide;
  }

  //...
}
  1. Create an EntryPoint for you ViewHolder and use it in the ViewHolder's constructor
public class SentenceViewHolder extends ViewHolder {

  @EntryPoint
  @InstallIn(ViewComponent.class)
  interface SentenceViewHolderEntryPoint {
    public ImageHelper imageHelper();
  }

  private ImageHelper imageHelper;  
  
  public SentenceViewHolder(View view, ItemTouchListener onItemTouchListener, OnStartDragListener mDragStartListener) {
    super(view);
    resolveDependency(view);
    this.v = view;
    findViewIds(onItemTouchListener, mDragStartListener);
  }

  private void resolveDependency(View view) {
    SentenceViewHolderEntryPoint hiltEntryPoint = EntryPointAccessors.fromView(view, SentenceViewHolderEntryPoint.class);
    imageHelper = hiltEntryPoint.imageHelper();
  }

  //...
}

Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132