Home > OS >  Android Studio calculate total price
Android Studio calculate total price

Time:10-09

I wanna ask how can I sum all patty price and display in the total ? The total is in activity_main.xml layout while all the product price is in view_product.xml . Screenshot of app As you can see the grey color text is per patty price , and the right side black text is price after multiply the quantity of patty. I want all the black text to sum up and show at below total.

MainActivity.java

package com.tankarjian.it212n.a2910assingment;

import android.app.Activity;
import android.os.Bundle;
import android.widget.BaseAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends Activity {

    private Products products;
    private BaseAdapter productsAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        products = createInitialProductList();
        productsAdapter = new ProductsAdapter(products, productClickListener, getLayoutInflater());

        ListView productsListView = (ListView) findViewById(R.id.products_list);
        productsListView.setAdapter(productsAdapter);
    }

    private Products createInitialProductList() {
        return new Products(new ArrayList<>(Arrays.asList(
                new Product("Chicken Patty", 0, 4.00),
                new Product("Chicken Special Patty", 0, 5.00),
                new Product("Imported Lamb Patty", 0, 8.00),
                new Product("Imported Lamb Special Patty", 0, 10.00)

        )));
    }

    private final ProductClickListener productClickListener = new ProductClickListener() {
        @Override
        public void onMinusClick(Product product) {
            products.removeOneFrom(product);
            productsAdapter.notifyDataSetChanged();
        }

        @Override
        public void onPlusClick(Product product) {
            products.addOneTo(product);
            productsAdapter.notifyDataSetChanged();
        }
    };

    private static class Products implements ProductDataSet {

        private final List<Product> productList;

        Products(List<Product> productList) {
            this.productList = productList;
        }

        @Override
        public int size() {
            return productList.size();
        }

        @Override
        public Product get(int position) {
            return productList.get(position);
        }

        @Override
        public long getId(int position) {
            return position;
        }

        public void removeOneFrom(Product product) {
            int i = productList.indexOf(product);
            if (i == -1) {
                throw new IndexOutOfBoundsException();
            }

            Product updatedProduct = new Product(product.name, (product.quantity - 1), product.getPrice());
            productList.remove(product);
            productList.add(i, updatedProduct);
        }

        public void addOneTo(Product product) {
            int i = productList.indexOf(product);
            if (i == -1) {
                throw new IndexOutOfBoundsException();
            }
            Product updatedProduct = new Product(product.name, (product.quantity   1), product.getPrice());
            productList.remove(product);
            productList.add(i, updatedProduct);
        }
    }

}

ProductsAdapter.java

package com.tankarjian.it212n.a2910assingment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Locale;

class ProductsAdapter extends BaseAdapter {

    private final ProductDataSet productDataSet;
    private final ProductClickListener productClickListener;
    private final LayoutInflater layoutInflater;

    ProductsAdapter(ProductDataSet productDataSet, ProductClickListener productClickListener, LayoutInflater layoutInflater) {
        this.productDataSet = productDataSet;
        this.productClickListener = productClickListener;
        this.layoutInflater = layoutInflater;
    }

    @Override
    public int getCount() {
        return productDataSet.size();
    }

    @Override
    public Product getItem(int position) {
        return productDataSet.get(position);
    }

    @Override
    public long getItemId(int position) {
        return productDataSet.getId(position);
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = createView(parent);
            view.setTag(ViewHolder.from(view));
        }

        Product Products =(Product) getItem(position);

        ImageView image = (ImageView) view.findViewById(R.id.imageBurgerView);
        image.setImageResource(R.drawable.burger);
        
        TextView text = (TextView) view.findViewById(R.id.singlePrice);
        String price = String.format(Locale.ENGLISH, "%.2f", Products.getPrice());
        text.setText(price);

        TextView text1 = (TextView) view.findViewById(R.id.totalPrice);
        String totalPrice = String.format(Locale.ENGLISH, "%.2f", (Products.getPrice() * Products.quantity));
        text1.setText(totalPrice);

        Product product = productDataSet.get(position);
        ViewHolder viewHolder = (ViewHolder) view.getTag();
        update(viewHolder, product);
        return view;


    }

    private View createView(ViewGroup parent) {
        return layoutInflater.inflate(R.layout.view_product, parent, false);
    }

    private void update(ViewHolder viewHolder, final Product product) {
        viewHolder.name.setText(product.name);
        viewHolder.quantity.setText(String.valueOf(product.quantity));
        viewHolder.minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                productClickListener.onMinusClick(product);
            }
        });
        viewHolder.plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                productClickListener.onPlusClick(product);
            }
        });
    }

    private static final class ViewHolder {
        final TextView name;
        final TextView quantity;
        final View minus;
        final View plus;

        static ViewHolder from(View view) {
            return new ViewHolder(
                    ((TextView) view.findViewById(R.id.product_name)),
                    ((TextView) view.findViewById(R.id.product_quantity)),
                    view.findViewById(R.id.product_minus),
                    view.findViewById(R.id.product_plus)

            );
        }

        private ViewHolder(TextView name, TextView quantity, View minus, View plus) {
            this.name = name;
            this.quantity = quantity;
            this.minus = minus;
            this.plus = plus;
        }
    }

}

Product.java

package com.tankarjian.it212n.a2910assingment;

class Product {
    final String name;
    final int quantity;
    private double price;

    Product(String name, int quantity, Double price) {
        this.name = name;
        this.quantity = quantity;
        this.price = price;

    }
    public double getPrice() {return price;}
}

activity_main.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="15dp"
    android:layout_marginTop="16dp"
    android:layout_marginEnd="15dp"
    android:layout_marginBottom="16dp"
    tools:context=".MainActivity">

    <ListView
        android:id="@ id/products_list"
        android:layout_width="0dp"
        android:layout_height="512dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <Switch
        android:id="@ id/switchMember"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="48dp"
        android:text="Member"
        app:layout_constraintEnd_toEndOf="@ id/products_list"
        app:layout_constraintTop_toBottomOf="@ id/products_list" />

    <TextView
        android:id="@ id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="25dp"
        android:layout_marginStart="16dp"
        android:text="Tax "
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintBottom_toTopOf="@ id/textView3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/products_list"
        app:layout_constraintVertical_bias="0.92" />

    <TextView
        android:id="@ id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="25dp"
        android:layout_marginBottom="68dp"
        android:text="Total "
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@ id/totalTax"
        android:layout_width="45dp"
        android:layout_height="wrap_content"
        android:text="0"
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@ id/textView2"
        app:layout_constraintTop_toTopOf="@ id/textView7" />

    <TextView
        android:id="@ id/textView9"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="5dp"
        android:text="RM"
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toStartOf="@ id/totalTax"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@ id/textView7"
        app:layout_constraintTop_toTopOf="@ id/textView7" />

    <TextView
        android:id="@ id/textView10"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="5dp"
        android:text="RM"
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toStartOf="@ id/finalTotalPrice"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@ id/textView8"
        app:layout_constraintTop_toTopOf="@ id/textView8" />

    <TextView
        android:id="@ id/finalTotalPrice"
        android:layout_width="45dp"
        android:layout_height="wrap_content"
        android:text="0"
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@ id/textView3"
        app:layout_constraintTop_toTopOf="@ id/textView8" />

    <TextView
        android:id="@ id/textView7"
        android:layout_width="210dp"
        android:layout_height="25dp"
        android:layout_marginStart="20dp"
        android:text="--------------------------------"
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toStartOf="@ id/totalTax"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toEndOf="@ id/textView2"
        app:layout_constraintTop_toTopOf="@ id/textView2" />

    <TextView
        android:id="@ id/textView8"
        android:layout_width="210dp"
        android:layout_height="26dp"
        android:layout_marginStart="20dp"
        android:text="--------------------------------"
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toStartOf="@ id/finalTotalPrice"
        app:layout_constraintHorizontal_bias="0.08"
        app:layout_constraintStart_toEndOf="@ id/textView3"
        app:layout_constraintTop_toTopOf="@ id/textView3" />

</androidx.constraintlayout.widget.ConstraintLayout>

view_product.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@ id/product_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#FF5722"
        android:textSize="20sp"
        android:textStyle="bold|italic" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@ id/imageBurgerView"
            android:layout_width="70dp"
            android:layout_height="60dp"
            android:layout_marginStart="10dp"
            android:contentDescription="@string/todo"
            app:srcCompat="@drawable/burger" />

        <TextView
            android:id="@ id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_weight="1"
            android:text="@string/rm"
            android:textAlignment="textEnd"
            android:textColor="#878BA3"
            android:textSize="16sp"
            android:textStyle="bold" />

        <TextView
            android:id="@ id/singlePrice"
            android:layout_width="108dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="3dp"
            android:layout_weight="1"
            android:text="@string/textview"
            android:textColor="#878BA3"
            android:textSize="16sp"
            android:textStyle="bold" />

        <TextView
            android:id="@ id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/rm"
            android:textAlignment="textEnd"
            android:textColor="#272E53"
            android:textSize="16sp"
            android:textStyle="bold|italic" />

        <TextView
            android:id="@ id/totalPrice"
            android:layout_width="45dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/textview"
            android:textAlignment="textStart"
            android:textColor="#272E53"
            android:textSize="16sp"
            android:textStyle="bold|italic" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="116dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@ id/product_minus"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:text="-"
            tools:ignore="TouchTargetSizeCheck" />

        <TextView
            android:id="@ id/product_quantity"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="20"
            android:textAlignment="center"
            android:textSize="16sp"
            android:textStyle="bold" />

        <Button
            android:id="@ id/product_plus"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:text=" "
            tools:ignore="TouchTargetSizeCheck" />

    </LinearLayout>


</LinearLayout>

CodePudding user response:

In view_product.xml you are only displaying the price, but that's not where the actual data is located so your question shouldn't be that the prices are in view_product.xml and you want to show in activity_main.xml, but your question should be -

  1. Where is the data located
  2. How to make the necessary calculations
  3. Where to show it. .

Your data regarding the prices are in products object. So, in order to calculate the total you just need to add one more method which calculates the total

private double calculateTotal(ProductDataSet productDataSet) {
    double totalPrice = 0.0;
    for(int i=0; i<productDataSet.size(); i  ) {
        totalPrice  = productDataSet.get(i).getPrice();
    }

    return totalPrice;
}

The result of this you can store in a new value or show directly in the textView itself.

((TextView)findViewById(R.id.finalTotalPrice)).setText(calculateTotal(products).toString());

This you can call anywhere after createInitialProductList(). I hope this helps and makes it clear for you.

  • Related