Mohammad Eskandari
Mohammad Eskandari

Reputation: 221

How to pass Context into Adapter with Dagger 2?

I'm learning DI/MVP/Retrofit/Rx base of this tutorial Dagger 2 Retrofit MVp .

And everything work perfect but I've got problem with using context in Adapter which if it wasn't just about intent i could use some method to open activity without using context, but i'm using library that named Picasso.

@Override
public void onBindViewHolder(@NonNull final BookViewHolder holder, final int position) {

    holder.txt_price.setText(new StringBuilder(bookList.get(position).Price).append(" تومان").toString());
    holder.txt_drink_name.setText(bookList.get(position).Name);

//        Picasso.with(context)
//                .load(bookList.get(position).Link)
//                .into(holder.img_product);

}

Before DI i was using Context context but now i can't just add this and use it for my Picasso library, which it's not really matter to use it or not, i just wanna know how to pass context

@Inject
public BookAdapter(ClickListener clickListener) {
    this.clickListener = clickListener;
    bookList = new ArrayList<>();
}

Everything I've did was base on above tutorial which the only thing is changed was my Picasso that was using context before.

I'm learning this, and i'm pretty fine with other steps i'm trying to figure out what should i do to make this possible, and should i create another module or whatever that can help.

Thanks.

Upvotes: 1

Views: 435

Answers (1)

David Medenjak
David Medenjak

Reputation: 34532

Just because you use Dagger doesn't mean you have to use it for everything. It makes often more sense not to use Dagger for UI / View related things.

In this case the simplest approach would be to use the views context.

@Override
public void onBindViewHolder(@NonNull final BookViewHolder holder, final int position) {
  final Context context = holder.itemView.getContext();

  Picasso.with(context)
    .load(bookList.get(position).Link)
    .into(holder.img_product);
}

Of course you can inject the context as well, if you feel inclined to do so. A context can be injected like any other object once you bind it to a component. One way is to bind it directly in your Component.Builder or Subcomponent.Builder using @BindsInstance.

Upvotes: 4

Related Questions