How to get a context in a recycler view adapter How to get a context in a recycler view adapter java java

How to get a context in a recycler view adapter


You have a 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 any View object. In your case this might work for you:

    holder.pub_image.getContext()

    As pub_image is a ImageView.


You can add global variable:

private Context context;

then assign the context from here:

@Overridepublic 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;@Overridepublic void onAttachedToRecyclerView(RecyclerView recyclerView) {    super.onAttachedToRecyclerView(recyclerView);    context = recyclerView.getContext();}

Explanation why other answers are not great:

  1. Passing Context to the adapter is completely unnecessary, since RecyclerView you can access it from inside the class
  2. Obtaining Context at ViewHolder level means that you do it every time you bind or create a ViewHolder. You duplicate operations.
  3. I don't think you need to worry about any memory leak. If your adapter lingers outside your Activity lifespan (which would be weird) then you already have a leak.