Candice
Candice

Reputation: 1

How to create dialog box when click on the item of recyclerview?

I'm trying to create a function that once a user clicks on the recycler view, a dialog box will pop out but I am stuck on the error as mentioned below. When I try to initialize AlertDialog.build and put this as the parameter, it shows an error. I had tried with a few other parameters like context, getActivity. But the error is still the same.

enter image description here

The code below is my full code

package com.example.tuitioncentre;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Observable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.firestore.DocumentSnapshot;

public class myadapter_tutorlist extends FirebaseRecyclerAdapter<User,myadapter_tutorlist.myviewholder> {

    AlertDialog.Builder builder;


    public myadapter_tutorlist(@NonNull FirebaseRecyclerOptions<User> options) {
        super(options);
    }

    @Override
    protected void onBindViewHolder(@NonNull final myviewholder holder, int position, @NonNull final User model) {

        holder.name.setText("Tutor's Name:" + model.getUsername());
        holder.phone.setText("Phone No:" + model.getPhone());
        holder.email.setText("Email:" + model.getEmail());
        holder.status.setText("Status: " + model.getActive().toString());
        builder = new AlertDialog.Builder(this);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                //Toast.makeText(v.getContext(),model.getUsername(),Toast.LENGTH_SHORT).show();

                builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
                builder.setMessage("Do you want to activate tutor account ?")
                        .setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Toast.makeText(v.getContext(),"you choose yes action for alertbox", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                //  Action for 'NO' Button
                                dialog.cancel();
                                Toast.makeText(v.getContext(),"you choose no action for alertbox", Toast.LENGTH_SHORT).show();
                            }
                        });
                //Creating dialog box
                AlertDialog alert = builder.create();
                //Setting the title manually
                alert.setTitle("AlertDialogExample");
                alert.show();
            }
        });
    }
    @NonNull
    @Override
    public myviewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //put singlerow xml into view holder
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow,parent,false);
        return new myviewholder(view);
    }


    class myviewholder extends RecyclerView.ViewHolder{
        TextView name,phone,email,status;
        public myviewholder(@NonNull View itemView) {
            super(itemView);
            name=(TextView)itemView.findViewById(R.id.nametext);
            phone=(TextView)itemView.findViewById(R.id.phonetext);
            email=(TextView)itemView.findViewById(R.id.emailtext);
            status=(TextView)itemView.findViewById(R.id.statustext);
        }
        
    }
}

Upvotes: 0

Views: 112

Answers (3)

Shailendra Madda
Shailendra Madda

Reputation: 21551

First pass the context from the Activity or Fragment:

For activity:

myadapter_tutorlist(options, this);

For Fragment:

myadapter_tutorlist(options, getActivity());

Then create a Context variable in side the Adapter class:

public class myadapter_tutorlist extends FirebaseRecyclerAdapter<User,myadapter_tutorlist.myviewholder> {

    AlertDialog.Builder builder;
    Context context;


    public myadapter_tutorlist(@NonNull FirebaseRecyclerOptions<User> options) {
        super(options);
        this.context = context;
    }

Now you can pass this context to your AlertDialog

builder = new AlertDialog.Builder(context);

Upvotes: 0

Amir Ehsani
Amir Ehsani

Reputation: 159

first create this class:

class RecyclerItemClickListener extends RecyclerView.SimpleOnItemTouchListener {
interface OnRecyclerClickListener{
    void onItemClick(View view, int position);
}

private final OnRecyclerClickListener mListener;
private final GestureDetectorCompat mGestureDetector;


public RecyclerItemClickListener(Context context, final RecyclerView recyclerView,
                                 OnRecyclerClickListener listener) {
    mListener = listener;

    mGestureDetector = new GestureDetectorCompat(context, new GestureDetector.SimpleOnGestureListener(){
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
          View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
            if (childView != null && mListener != null){
                Log.d(TAG, "onSingleTapUp: calling listener.onItemClick");
                mListener.onItemClick(childView, recyclerView.getChildAdapterPosition(childView));
            }
            return true;
        }
});
}

@Override
public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
    if (mGestureDetector != null){
        boolean result = mGestureDetector.onTouchEvent(e);
        return result;
    } else {
        return false;
    }
}
}

and in MainActivity:

in onCreate method: first define recyclerView variable by findviewbyid() then:

        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, this));

then implement onItemClick() method. you can define alert dialog here:

@Override
public void onItemClick(View view, int position) {
    Toast.makeText(this, "normal tap on position " + position, Toast.LENGTH_SHORT).show();

}

Upvotes: 0

Yash Joshi
Yash Joshi

Reputation: 627

Passing "this" to AlertDialog.Builder(this); won't work as you're trying to pass a reference of your Adapter.

There are two correct ways to achieve this:

Add a variable to reference your Activity like Activity mActivity; in your Adapter class. Then, in your Activity class where you're initializing the Adapter, you can pass your activity context as "this". You can achieve it either with a constructor in the Adapter class or in your Activity class use your adapter instance once it is initialized to access the mActivity variable and set it.

Alternatively, you can use a view interface and implement it in your activity, override the method to show the AlertDialog in your activity. Then add a reference variable of that interface in your Adapter like SomeInterface mInfterface; and initialize it in your Activity class the same way mentioned above. Then you can just call that method to show the AlertDialog and pass the data to that method from the Adapter to show all information like -

mInterface.showAlertDialog(model);

Upvotes: 3

Related Questions