Yasser B. Yasser B. - 6 months ago 135
Android Question

How to get a context in a recycler view adapter

I'm trying to use picasso library to be able to load url to imageView, but I'm not able to get the

to use the picasso library correctly.

public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.ViewHolder> {
private List<Post> mDataset;

// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView txtHeader;
public ImageView pub_image;
public ViewHolder(View v) {
txtHeader = (TextView) v.findViewById(R.id.firstline);
pub_image = (ImageView) v.findViewById(R.id.imageView);


// Provide a suitable constructor (depends on the kind of dataset)
public FeedAdapter(List<Post> myDataset) {
mDataset = myDataset;

// Create new views (invoked by the layout manager)
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);
return vh;

// Replace the contents of a view (invoked by the layout manager)
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element




// Return the size of your dataset (invoked by the layout manager)
public int getItemCount() {
return mDataset.size();



You have w few options here:

  1. Pass Context as an argument to FeedAdapter and keep it as class field
  2. Use dependency injection to inject Context when you need it. I strongly suggest reading about it. There is a great tool for that -- Dagger by Square
  3. Get it from ... View object. In your case this might work for you


    as pub_image is a ImageView, right?