androidandroid-recyclerviewonitemclicklisteneronitemclick

RecyclerView onItemClick not working, always show nullpointerexception


I checked full of Stackoverflow but i can't find solution, May be this is duplicate question but please help me. i create Interface in Adapter:-

public interface OnItemClickListener {
    void onItemClick(int positon, AdvSearchList_Model item, View view);
}
public MyMatches_New_Adapter(Context context, ArrayList<AdvSearchList_Model> dataList, OnItemClickListener listener) {
    this.context = context;
    this.listItem = dataList;
    this.listener = listener;
}

In onBindViewHolder:-

final AdvSearchList_Model item = listItem.get(position);
        myholder.setIsRecyclable(false);
        myholder.bind(position, item, listener);

Call bind function:-

public void bind(final int position, final AdvSearchList_Model item, final MyMatches_New_Adapter.OnItemClickListener listener) {
                itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onItemClick(position, item, v);
                }
            });
            user_pic_circle_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onItemClick(position, item, v);
                }
            });}

and set onItemClick in Fragment Class:-

adapter1 = new MyMatches_New_Adapter(context, listItem, new MyMatches_New_Adapter.OnItemClickListener() {
        @Override
        public void onItemClick(int positon, final AdvSearchList_Model item, View view) {
            switch (view.getId()) {
                case R.id.user_pic_circle_layout:
                    Toast.makeText(context, "COMMENT Working", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    });

When i click on Item then its give me NullPointerException. Please do the needfull.


Solution

  • add this method in your adapter -

     public void setOnItemListener(Context context, ArrayList<AdvSearchList_Model> dataList, OnItemClickListener listener) {    
        this.context = context;
        this.listItem = dataList;
        this.listener = listener;
     }
    

    access your fragment -

    adapter1.setOnItemListener(context, listItem, new MyMatches_New_Adapter.OnItemClickListener() {
            @Override
            public void onItemClick(int positon, final AdvSearchList_Model item, View view) {
                switch (view.getId()) {
                    case R.id.user_pic_circle_layout:
                        Toast.makeText(context, "COMMENT Working", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });