Home > Back-end >  Pass data from recyclerView to new activity when an item is clicked Kotlin
Pass data from recyclerView to new activity when an item is clicked Kotlin

Time:03-03

I have a recyclerView which displays items in cardview with the data from firebase database. I did the coding for launching a new activity when an item is clicked. Now I want to pass the data of the item clicked from the recyclerView to the new activity so that I can display the data in it. I am using kotlin. I watched few videos on yt and tried few methods. As I am a beginner I need help in solving this. Thanks in advance.

I have an RecyclerItemClickListener which launches the new activity when an item is clicked.

RecyclerView class

class storekotlin : Fragment() {
private var param1: String? = null
private var param2: String? = null

var recyclerView: RecyclerView? = null

var productlist = ArrayList<Product>()
private var database: FirebaseDatabase? = null
private var reference: DatabaseReference? = null


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    arguments?.let {
        param1 = it.getString(ARG_PARAM1)
        param2 = it.getString(ARG_PARAM2)
    }
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    var view =  inflater.inflate(R.layout.fragment_storekotlin, container, false)

    database = FirebaseDatabase.getInstance()
    reference = database?.getReference("Products")

    val FirebaseListener = object: ValueEventListener {
        override fun onDataChange(p0: DataSnapshot) {

            val child = p0.children
            child.forEach{

                var products = Product(it.child("img").value.toString(), 
it.child("name").value.toString(), it.child("price").value.toString())

                productlist.add(products)

            }


            val adapter = ProductAdapter(productlist)
            recyclerView?.adapter = adapter

        }

        override fun onCancelled(p0: DatabaseError) {

        }


    }
    reference?.addValueEventListener(FirebaseListener)

    recyclerView = view.findViewById(R.id.recyclerview)
    recyclerView?.setHasFixedSize(true)
    recyclerView?.layoutManager = GridLayoutManager(activity, 1, 
GridLayoutManager.VERTICAL, false)

    val defuserimg: ImageView = view.findViewById(R.id.defuserimg)
    val defuser: TextView = view.findViewById(R.id.defuser)
    val info:  ImageView = view.findViewById(R.id.info)
    val search: EditText = view.findViewById(R.id.search)

    defuserimg.setOnClickListener {
        val intent = Intent(activity, signin_page::class.java)
        startActivity(intent)
    }

    defuser.setOnClickListener {
        val intent = Intent(activity, signin_page::class.java)
        startActivity(intent)
    }

    info.setOnClickListener {
        val intent = Intent(activity, aboutpage::class.java)
        startActivity(intent)
    }

    recyclerView?.addOnItemTouchListener(
        RecyclerItemClickListener(
            activity, recyclerView!!, object : 
RecyclerItemClickListener.OnItemClickListener {
                override fun onItemClick(view: View, position: Int) {

                    val intent = Intent(activity, productdetails::class.java)
                    startActivity(intent)

                }

                override fun onLongItemClick(view: View, position: Int) {
                }
            })
    )

    return view

}



companion object {

    @JvmStatic
    fun newInstance(param1: String, param2: String) =
        storekotlin().apply {
            arguments = Bundle().apply {
                putString(ARG_PARAM1, param1)
                putString(ARG_PARAM2, param2)
            }
        }
}

}

RecyclerAdapter class

class ProductAdapter(private var productlist:MutableList<Product>): 
RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() {

override fun onCreateViewHolder(
    parent: ViewGroup,
    viewType: Int
): ProductViewHolder {

    val layoutView:View = 
LayoutInflater.from(parent.context).inflate(R.layout.itemcard,parent,false)
    return ProductViewHolder(layoutView)

}

override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {

    Picasso.get().load(productlist[position].prdimg).into(holder.prdimg)
    holder.prdname.text = productlist[position].prdname
    holder.prdprice.text = productlist[position].prdprice


}

override fun getItemCount(): Int {
    return productlist.size;
}

inner class ProductViewHolder(view: View): RecyclerView.ViewHolder(view){

    var prdimg: ImageView = view.findViewById(R.id.prdimg)
    var prdname: TextView = view.findViewById(R.id.prdname)
    var prdprice: TextView = view.findViewById(R.id.prdprice)



}

CodePudding user response:

easiest way

in adapter class do like

class ProductAdapter(val fragment: storekotlin,private var productlist:MutableList<Product>): 
RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() {

override fun onCreateViewHolder(
    parent: ViewGroup,
    viewType: Int
): ProductViewHolder {

    val layoutView:View = 
LayoutInflater.from(parent.context).inflate(R.layout.itemcard,parent,false)
    return ProductViewHolder(layoutView)

}

override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {

    Picasso.get().load(productlist[position].prdimg).into(holder.prdimg)
    holder.prdname.text = productlist[position].prdname
    holder.prdprice.text = productlist[position].prdprice
 
 holder.itemView.setOnClickListener {
            val name = productlist[position].prdname
             val price= productlist[position].prdprice
            fragment.deatailsList(name , price) // here you can send just the position it will be more efficient
        }
}

override fun getItemCount(): Int {
    return productlist.size;
}

inner class ProductViewHolder(view: View): RecyclerView.ViewHolder(view){

    var prdimg: ImageView = view.findViewById(R.id.prdimg)
    var prdname: TextView = view.findViewById(R.id.prdname)
    var prdprice: TextView = view.findViewById(R.id.prdprice)

}

in storekotlin Fragment onCreateView method pass the list and fragment like this

   val adapter = ProductAdapter(this@storekotlin,productlist)
            recyclerView?.adapter = adapter

in storekotlin activity create another method

  fun deatailsList(name: String, price: String?) {

        // Log.d(ContentValues.TAG, "myList:${dataList.size}")

        val intent = Intent(requireContext(), DetailsActivity::class.java)

        intent.putExtra("nameKey", name)
        intent.putExtra("priceKey", price)
       
        startActivity(intent)
    }

in Details activity onCreate method

   val intent = intent
      
        val rcvName = intent.getStringExtra("nameKey")
        val rcvPrice= intent.getStringExtra("priceKey")

  // now you can print here the selected value 
    textDayIncome_id.text = rcvName 
    textDayExpense_id.text = rcvPrice
  • Related