0

I am trying to create an AlertDialog pop up when a button inside a recycler view is clicked as follow:

class productItems(val user: DataProduk): Item<GroupieViewHolder>() {
    lateinit var uid: String
    lateinit var auth: FirebaseAuth

    override fun bind(viewHolder: GroupieViewHolder, position: Int) {
        auth = FirebaseAuth.getInstance()
        uid = auth.currentUser?.uid.toString()
      
        viewHolder.itemView.product_name_title.text = user.productName
        viewHolder.itemView.delete_product_button.setOnClickListener {
            val builder = AlertDialog.Builder(context)
            val dialog = DialogInterface
            builder.setTitle("Delete")
                .setMessage("Are you sure you want to delete ?")
                .setPositiveButton("DELETE", DialogInterface.OnClickListener(dialog: DialogInterface){
                    
                })
                .show()
        }
        Picasso.get().load(user.fotoProdukUri).into(viewHolder.itemView.foto_produk_daftar)
    }
    override fun getLayout(): Int {
        return R.layout.product_list
    }
}

But the val builder = AlertDialog.Builder() requires a context inside the round brackets. when I use requireContext(), it says no value passed for parameter 'provider'. So what need to be put in it?

Tommy -
  • 53
  • 9
  • 1
    You shouldn't. You should do it on the host with a callback [Recycler View Callback to activity](https://stackoverflow.com/questions/61802011/recycler-view-callback-to-activity). If you really want to insist on doing it there, then get the context from any view. Also, you shouldn't be calling Firebase from inside the recycler. – cutiko Aug 22 '22 at 14:07
  • 1
    There's lots of ways to access a `Context` inside a `ViewHolder`, e.g. pass it into your `Adapter`'s constructor and make that parameter a `val` so it's a stored property, then either make the `ViewHolder` an `inner` class so it can see the property, or pass it into the `ViewHolder`'s constructor. But *cutiko*'s right, the VH shouldn't be responsible for things like displaying dialogs or doing Firebase operations. Just generate a click event (e.g. by calling a function on the containing `Fragment`) and pass the important info (like the position clicked) and let something else handle it – cactustictacs Aug 22 '22 at 19:46
  • @cactustictacs thanks, making `viewHolder` the context's parameter solves it. So the final code is `AlertDialog.Builder(viewHolder.itemView.context)` Thank you. – Tommy - Aug 23 '22 at 11:12

0 Answers0