Home > Blockchain >  Passing data from an activity (On Button clicked), to be added to a recyclerView adapter at another
Passing data from an activity (On Button clicked), to be added to a recyclerView adapter at another

Time:01-13

I'm trying to make a food application with android-Kotlin, and it contains: The problem is i tried many times to send data from "PopularDetailedActivity" to another activity onClick (Add To Cart Button) which contains my Cart or basket that i choose, but i can't access a solution.

PopularAdapter.kt that pass the data to PopularDetailedActivity.kt

class PopularAdapter(private var popItems: List<Popular>): RecyclerView.Adapter<PopularAdapter.MyViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val popView = LayoutInflater.from(parent.context).inflate(R.layout.pop_items, parent, false)
        return MyViewHolder(popView)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val newPop: Popular = popItems[position]
        holder.foodName.text = newPop.foodName
        holder.foodImg.setImageResource(newPop.foodImage)
        holder.foodDollar.text = newPop.foodDollar
        holder.foodPrice.text = newPop.foodPrice.toString()
        holder.foodDetails.text = newPop.foodDetails
        holder.myPop = newPop
    }

    override fun getItemCount(): Int {
        return popItems.size
    }
    fun submitList(categories: List<Popular>){
        popItems = categories
    }
    class MyViewHolder constructor(itemView: View, var myPop: Popular?= null):
        RecyclerView.ViewHolder(itemView){
        init {
            itemView.addBtn.setOnClickListener {
                val myIntent = Intent(itemView.context, PopularDetailed::class.java)
                myIntent.putExtra("title", myPop!!.foodName)
                myIntent.putExtra("price", myPop!!.foodPrice)
                myIntent.putExtra("img", myPop!!.foodImage)
                myIntent.putExtra("description", myPop!!.foodDetails)
                itemView.context.startActivity(myIntent)
            }
        }
        val foodName: TextView = itemView.popMainText
        val foodImg: ShapeableImageView = itemView.popMainImg
        val foodDollar: TextView = itemView.dollarTxt
        val foodPrice: TextView = itemView.priceValue
        val foodDetails: TextView = itemView.popDetail
    }
}

PopularDetailedActivity.kt

class PopularDetailed : AppCompatActivity() {
    private lateinit var cTitle: TextView
    private lateinit var cImage: ShapeableImageView
    private lateinit var cPrice: TextView
    private lateinit var cDollar: TextView
    private lateinit var cMinus: ImageView
    private lateinit var cPlus: ImageView
    private lateinit var cItemVal: TextView
    private lateinit var cDescription: TextView
    private lateinit var cAddBtn: Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_popular_details)
        val bundle = intent.extras
        val localTitle = bundle!!.getString("title")
        val localPrice = bundle.getDouble("price")
        val localImage = bundle.getInt("img")
        val localDescription = bundle.getString("description")
        initValues()
        cTitle.text = localTitle
        cPrice.text = localPrice.toString()
        cImage.setImageResource(localImage)
        cDescription.text = localDescription
        
        incDecNum()
        
        cAddBtn.setOnClickListener {
            if (incDecValue.text.toString().toInt() > 0){
                Toast.makeText(applicationContext, "Added To Your Cart", Toast.LENGTH_SHORT).show()
            }
        }
    }
    //Initiate Values
    private fun initValues(){
        cTitle = findViewById(R.id.pop_local_title)
        cImage = findViewById(R.id.pop_local_img)
        cPrice = findViewById(R.id.localPriceValue)
        cDollar = findViewById(R.id.localDollarTxt)
        cPlus = findViewById(R.id.incNum)
        cItemVal = findViewById(R.id.incDecValue)
        cMinus = findViewById(R.id.decNum)
        cDescription = findViewById(R.id.pop_local_des)
        cAddBtn = findViewById(R.id.local_add_btn)
    }
    //Increase or decrease items' number
    private fun incDecNum(){
        
        val priceValueInString = localPriceValue.toString()
        var priceInDouble = priceValueInString.split("")[0].toDoubleOrNull()
        
        val incDecValueInString = incDecValue.toString()
        var numberOfItems = incDecValueInString.split(" ")[0].toIntOrNull()
        numberOfItems = 0
        decNum.setOnClickListener {
            if (numberOfItems > 0){
                numberOfItems -= 1
                val newVal = numberOfItems.toString()
                incDecValue.text = newVal
                //Changing the price
                /*if (priceInDouble != null) {
                    if (newVal > 0.toString()){
                        priceInDouble -= priceInDouble
                        localPriceValue.text = priceInDouble.toString()
                    }
                }*/
            } else{
                //Toast.makeText(applicationContext, "", Toast.LENGTH_SHORT).show()
            }
        }
        incNum.setOnClickListener {
            numberOfItems  = 1
            val newVal = numberOfItems.toString()
            incDecValue.text = newVal
            //Changing the price
            /*if (priceInDouble != null) {
                if (newVal > 1.toString()){
                    priceInDouble  = priceInDouble
                    localPriceValue.text = priceInDouble.toString()
                }
            }*/
        }
    }
}

MyCartBasketActivity.kt

class MyCartBasket : AppCompatActivity() {
    private val myCartItems = ArrayList<MyCart>()
    private val myCartAdapter = MyCartAdapter(myCartItems)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_cart_basket)
        myCartDynamic.layoutManager = LinearLayoutManager(applicationContext, RecyclerView.VERTICAL, false)
        myCartDynamic.adapter = myCartAdapter
    }
    //Adding Data
    /*private fun addData(){
        val cartItems = MyCartDynamicDataSource.createDynamicCartItems(myCartItems)
        myCartAdapter.submitList(cartItems)
    }*/
}

MyCartAdapter.kt for the result activity at MyCartBasketActivity.kt

class MyCartAdapter(private var cartItems: List<MyCart>):
    RecyclerView.Adapter<MyCartAdapter.MyViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val cartView = LayoutInflater.from(parent.context).inflate(R.layout.my_cart_items, parent, false)
        return MyViewHolder(cartView)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val newCart = cartItems[position]
        holder.cartedImg.setImageResource(newCart.cartedImg)
        holder.cartedTitle.text = newCart.cartedTitle
        holder.cartedItemNum.text = newCart.cartedItemNum
        holder.cartedLPriceValue.text = newCart.cartedLPriceValue
        holder.cartedIPriceValue.text = newCart.cartedIPriceValue
        holder.cartedPlusItem.text = newCart.cartedPlusItem
        holder.cartedMinusItem.text = newCart.cartedMinusItem
    }

    fun submitList(cartNewItems: List<MyCart>){
        cartItems = cartNewItems
    }

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

    class MyViewHolder constructor(itemView: View): RecyclerView.ViewHolder(itemView){
        val cartedImg: ShapeableImageView = itemView.myCartedImg
        val cartedTitle: TextView = itemView.myCartedTitle
        val cartedItemNum: TextView = itemView.myCartItemNum
        val cartedLPriceValue: TextView = itemView.localPriceCart
        val cartedIPriceValue: TextView = itemView.localPriceCartA
        val cartedPlusItem: Button = itemView.incNumCart
        val cartedMinusItem: Button = itemView.decNumCart
    }
}

Popular.kt

class Popular {
    var foodName:String
    var foodImage:Int
    var foodDollar:String
    var foodPrice:Double
    var foodDetails:String
    constructor(foodName:String, foodImg:Int, foodDollar:String, foodPrice:Double, foodDetails:String){
        this.foodName = foodName
        this.foodImage = foodImg
        this.foodDollar = foodDollar
        this.foodPrice = foodPrice
        this.foodDetails = foodDetails
    }

activity_popular_details.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginStart="25dp"
    android:layout_marginEnd="25dp"
    tools:context=".PopularDetailed">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@ id/pop_local_title"
        android:theme="@style/MyPopLocalText"
        android:text="@string/hello_blank_fragment"
        android:layout_marginTop="35dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@ id/local_price"
        android:orientation="horizontal"
        android:layout_marginTop="15dp"
        app:layout_constraintTop_toBottomOf="@id/pop_local_title"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent">

        <TextView
            android:id="@ id/localDollarTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/dollarSign"
            android:textColor="@android:color/holo_orange_light"
            android:textSize="16sp"
            tools:ignore="TextContrastCheck" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@ id/localPriceValue"
            android:text="@string/price_val"
            android:textStyle="bold"
            android:textColor="@color/black"
            android:textSize="16sp"/>
    </LinearLayout>
    <com.google.android.material.imageview.ShapeableImageView
        android:layout_width="300dp"
        android:layout_height="350dp"
        android:id="@ id/pop_local_img"
        android:src="@drawable/hot_breakfast"
        android:layout_marginTop="5dp"
        app:layout_constraintTop_toBottomOf="@id/local_price"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@ id/incDecItemNum"
        android:orientation="horizontal"
        app:layout_constraintTop_toBottomOf="@id/pop_local_img"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent">
        <ImageView
            android:layout_width="35dp"
            android:layout_height="35dp"
            android:id="@ id/decNum"
            android:contentDescription="@string/dollarSign"
            android:background="@drawable/inc_dec_back"
            android:src="@drawable/minus"
            tools:ignore="TouchTargetSizeCheck"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@ id/incDecValue"
            android:text="@string/_0"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            android:textSize="15sp"
            android:textStyle="bold"
            android:textColor="@color/black"
            app:layout_constraintStart_toEndOf="@id/decNum"
            app:layout_constraintTop_toTopOf="@id/decNum"
            app:layout_constraintBottom_toBottomOf="@id/decNum"/>
        <ImageView
            android:layout_width="35dp"
            android:layout_height="35dp"
            android:id="@ id/incNum"
            android:layout_marginStart="8dp"
            android:contentDescription="@string/dollarSign"
            android:background="@drawable/inc_dec_back"
            android:src="@drawable/plus"
            tools:ignore="TouchTargetSizeCheck"
            app:layout_constraintTop_toTopOf="@id/decNum"
            app:layout_constraintStart_toEndOf="@id/incDecValue"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@ id/pop_local_des"
        android:text="@string/meal_description"
        android:layout_marginTop="10dp"
        android:theme="@style/MyPopLocalDes"
        app:layout_constraintTop_toBottomOf="@id/incDecItemNum"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@ id/local_add_btn"
        android:backgroundTint="#FF5E00"
        android:text="@string/add_to_cart"
        android:textStyle="bold"
        android:textSize="17sp"
        app:shapeAppearanceOverlay="@style/Button5"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

activity_my_cart_basket.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyCartBasket">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@ id/maiCartV"
        android:layout_marginBottom="50dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@ id/myCartView"
            android:orientation="vertical"
            android:layout_marginTop="15dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@ id/myCartMainText"
                android:text="@string/your_cart"
                android:theme="@style/MyHeadText"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"/>

            <androidx.recyclerview.widget.RecyclerView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:id="@ id/myCartDynamic"
                android:layout_marginTop="15dp"/>

        </LinearLayout>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@ id/itemsTotalPrice"
            android:orientation="horizontal"
            android:layout_marginTop="25dp"
            app:layout_constraintTop_toBottomOf="@id/myCartView"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@ id/totalPriceText"
                android:layout_marginStart="15dp"
                android:text="@string/items_total_price"
                android:textStyle="bold"
                android:textColor="@color/black"
                android:textSize="16sp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@ id/mainTotalValue"
                android:text="@string/_0"
                android:layout_marginEnd="15dp"
                android:textColor="@color/black"
                android:textSize="13sp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"/>

            <TextView
                android:id="@ id/mainTotalDollar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="5dp"
                android:text="@string/dollarSign"
                android:textColor="#FF5E00"
                android:textSize="13sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toStartOf="@id/mainTotalValue"
                app:layout_constraintTop_toTopOf="parent"
                tools:ignore="TextContrastCheck" />


        </androidx.constraintlayout.widget.ConstraintLayout>
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@ id/itemsDeliveryPrice"
            android:orientation="horizontal"
            android:layout_marginTop="10dp"
            app:layout_constraintTop_toBottomOf="@id/itemsTotalPrice"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@ id/totalDeliveryText"
                android:layout_marginStart="15dp"
                android:text="@string/delivery_services"
                android:textStyle="bold"
                android:textColor="@color/black"
                android:textSize="16sp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@ id/mainDeliveryValue"
                android:text="@string/_0"
                android:layout_marginEnd="15dp"
                android:textColor="@color/black"
                android:textSize="13sp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"/>

            <TextView
                android:id="@ id/mainDeliveryDollar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="5dp"
                android:text="@string/dollarSign"
                android:textColor="#FF5E00"
                android:textSize="13sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toStartOf="@id/mainDeliveryValue"
                app:layout_constraintTop_toTopOf="parent"
                tools:ignore="TextContrastCheck" />


        </androidx.constraintlayout.widget.ConstraintLayout>
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@ id/itemsTaxPrice"
            android:orientation="horizontal"
            android:layout_marginTop="10dp"
            app:layout_constraintTop_toBottomOf="@id/itemsDeliveryPrice"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@ id/totalTaxText"
                android:layout_marginStart="15dp"
                android:text="@string/taxes"
                android:textStyle="bold"
                android:textColor="@color/black"
                android:textSize="16sp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@ id/mainTaxValue"
                android:text="@string/_0"
                android:layout_marginEnd="15dp"
                android:textColor="@color/black"
                android:textSize="13sp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"/>

            <TextView
                android:id="@ id/mainTaxDollar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="5dp"
                android:text="@string/dollarSign"
                android:textColor="#FF5E00"
                android:textSize="13sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toStartOf="@id/mainTaxValue"
                app:layout_constraintTop_toTopOf="parent"
                tools:ignore="TextContrastCheck" />


        </androidx.constraintlayout.widget.ConstraintLayout>
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@ id/itemsTotal"
            android:orientation="horizontal"
            android:layout_marginTop="25dp"
            app:layout_constraintTop_toBottomOf="@id/itemsTaxPrice"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@ id/totalTotalText"
                android:layout_marginStart="15dp"
                android:text="@string/total"
                android:textStyle="bold"
                android:textColor="@color/black"
                android:textSize="25sp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@ id/mainTotalV"
                android:text="@string/_0"
                android:layout_marginEnd="15dp"
                android:textColor="@color/black"
                android:textSize="18sp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"/>

            <TextView
                android:id="@ id/mainTotalD"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="5dp"
                android:text="@string/dollarSign"
                android:textColor="#FF5E00"
                android:textSize="18sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toStartOf="@id/mainTotalV"
                app:layout_constraintTop_toTopOf="parent"
                tools:ignore="TextContrastCheck" />


        </androidx.constraintlayout.widget.ConstraintLayout>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@ id/cart_check_btn"
            android:backgroundTint="#FF5E00"
            android:text="@string/checkout"
            android:textStyle="bold"
            android:textSize="25sp"
            android:layout_marginStart="50dp"
            android:layout_marginEnd="50dp"
            android:layout_marginBottom="35dp"
            app:shapeAppearanceOverlay="@style/Button5"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"/>
    </androidx.constraintlayout.widget.ConstraintLayout>

    <include layout="@layout/bottom_bar"/>

</androidx.constraintlayout.widget.ConstraintLayout>

I want to add the data which viewed at "PopularDetailedActivity" to "MyCartActivity" without starting it, and then to the adapter of its dynamic recyclerView, and update it. But, i can't access the proper solution.

CodePudding user response:

You need to persist basket data somehow, then pass data itself (or reference to this data) to new screen (MyCartActivity).

The tricky question is to how to persist the data.

IMO, good solution can be to use fragments instead of activities, then you can use sharedViewModel, where you store data with basket items. This shared view model will be accessible by both fragments.

If for some reason you can't use fragments (although I strongly advise to do so), then another solution may be to have some singleton object, where you store basket items. Note though, that usage of singleton objects is risky - for example, when you start updating data in singletons from different places, you may loose control on it at some point in time.

object TempBasketDataHolder {
    val basketItems: MutableList<Popular> = mutableListOf()
}

Then in your PopularDetailedActivity you can define methods to handle basket content:

fun clearBasket() {
        TempBasketDataHolder.basketItems.clear()
    }
    
    fun addBasketItem(item: Popular) {
        TempBasketDataHolder.basketItems.add(item)
    }

    fun removeBasketItem(item: Popular) {
        TempBasketDataHolder.basketItems.remove(item)
    }

In your MyCartActivity you can then access TempBasketDataHolder.basketItems correspondingly.

  • Related