Patrick J. Patrick J. - 1 year ago 106
Android Question

Context error in Adapter for RecyclerView

In my Adapter for my RecyclerView I trying to text whenever text is clicked on each row but I am getting a context error. I'm a beginner programmer so I'm not sure what to do. Thanks in advance. Also I'm trying to create an app where in each row there is a messaging group chat that everyone can see and each user has the ability to add a row with whatever title they choose. If someone could help me with that, it would be awesome! And be very appreciated because I'm pretty novice. Thank you!

The error I'm getting takes place where I have my toast where it says context.

Adaper code:

package com.example.patri.index01;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private LayoutInflater inflater;
List<Information> data= Collections.emptyList();

public MyAdapter(Context context, List<Information> data){

public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

View view=inflater.inflate(R.layout.custom_row, parent,false);
MyViewHolder holder=new MyViewHolder(view);
return holder;

public void onBindViewHolder(MyViewHolder holder, final int position) {

Information current=data.get(position);


holder.title.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(context, "Item clicked at " +position, Toast.LENGTH_SHORT)


public int getItemCount() {
return data.size();

class MyViewHolder extends RecyclerView.ViewHolder{
TextView title;

ImageView icon;

public MyViewHolder(View itemView) {


title= (TextView)itemView.findViewById(;

icon= (ImageView) itemView.findViewById(;


Information class:

public class Information {

int iconId;

String title;


Answer Source

Problem is getting because context is not accessible inside onClick method which is passed in MyAdapter class Constructor.

In onClick method use v.getContext() :

  Toast.makeText(v.getContext(), "Item clicked at " +position, Toast.LENGTH_SHORT)


Declare context in MyAdapter class and initialize it in Constructor:

Context context;
public MyAdapter(Context context, List<Information> data){

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download