Passing Context to the adapter is completely unnecessary, since RecyclerView you can access it from inside the class. Obtaining Context at ViewHolder level means that you do it every time you bind or create a ViewHolder . You duplicate operations.
there is nothing wrong with passing context to your adapter. You just should keep your adapter responsible for work with views, leaving networking or database operations for your fragment.
You have a few options here:
Context
as an argument to FeedAdapter and keep it as class fieldContext
when you need it. I strongly suggest reading about it. There is a great tool for that -- Dagger by SquareGet it from any View
object. In your case this might work for you:
holder.pub_image.getContext()
As pub_image
is a ImageView
.
Edit As solidak said in the comments section, the original answer could lead to memory leak issues, and it's a bad practice to use this method, so it's better to use another method to access the context.
Original answer:
You can add a global variable:
private Context context;
then assign the context from here:
@Override
public FeedAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// create a new view
View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.feedholder, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
// set the Context here
context = parent.getContext();
return vh;
}
Happy Codding :)
Short answer:
Context context;
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
context = recyclerView.getContext();
}
Explanation why other answers are not great:
Context
to the adapter is completely unnecessary, since RecyclerView
you can access it from inside the classContext
at ViewHolder
level means that you do it every time you bind or create a ViewHolder
. You duplicate operations.Activity
lifespan (which would be weird) then you already have a leak.You can use pub_image context (holder.pub_image.getContext()
) :
@Override
public void onBindViewHolder(ViewHolder ViewHolder, int position) {
holder.txtHeader.setText(mDataset.get(position).getPost_text());
Picasso.with(holder.pub_image.getContext()).load("http://i.imgur.com/DvpvklR.png").into(holder.pub_image);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With