Made onClick() in onBindViewHolder() , but there is a small problem. It turns out NullPointerExeption, but logging works fine, gives all positions, stumbles on the dialogue, I think this is possible because of the context , I asked it this way:

  public Context context; 

I set it this way, because neither getContext() nor anything else works.

C onBindViewHolder() :

  @Override public void onBindViewHolder(final ViewHolder holder, int position) { holder.mTextView.setText(mDataset.get(position)); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "position = " + holder.getAdapterPosition()); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("tittle") .setMessage("hi") .setCancelable(false) .setNegativeButton("закрыть", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } }); } 

PS I just pointed it to the base of the class, as I wrote above (as suggested by Android Studio). I'm pretty sure that because of this is null , but I don't know how else to get the Context . Previously, it always saved getContext() , getActivity() in such cases.

    2 answers 2

    If you just wrote:

     public Context context; 

    and calculate that this way you get the context, it is not. With this line, you simply created a link called context to hold an object of the Context class. The object itself is absent (not received), because the context is not just some word, but an object containing certain data and in order to use it, this data must first be obtained from the classes that contain this information.

    There are two ways to solve the problem:

    1. Pass the context from the activation or fragment (which has context information) through the adapter's constructor.

    2. Get context from any View in adapter

    In the case of a dialogue, it is recommended to use an activ context, since in the context of a View may be other information, for example, about the topic being used, etc.

    PS: The getContext() and getActivity() methods are methods of the Activity and Fragment classes. The adapter is not inherited from these classes and these methods are missing in it. Also, the adapter is not a successor of any classes that have context and inside it for direct access.

    PPS: making class fields that are used only inside a class is strongly discouraged.

      It was necessary to use holder and itemView. holder.itemView.getContext()