skip to Main Content

I’m developing activity and it displays the itemName, itenQty and price of an item set in the Recycler View. I want to get the total price of all the items. How can I use for loop or another way to get the grand total.

private static class ViewHolder extends RecyclerView.ViewHolder {

    private AppCompatEditText txtProductName, txtQuantity, txtPrice;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        txtProductName = itemView.findViewById(R.id.inputDescription);
        txtQuantity = itemView.findViewById(R.id.inputQty);
        txtPrice = itemView.findViewById(R.id.inputPrice);
    }

    void bind(PurchaseOrderDT dt) {
        txtProductName.setText(dt.getItemDescription());
        txtQuantity.setText(String.format(Locale.ENGLISH, "%d", dt.getQty()));
        txtPrice.setText(String.format(Locale.ENGLISH, "%,.2f", dt.getPrice()));

        //getting grand total of item prices

    }
}

PurchaseOrderDT Class

public class PurchaseOrderDT extends Product implements Parcelable {

    public static final Creator<PurchaseOrderDT> CREATOR = new Creator<PurchaseOrderDT>() {
        @Override
        public PurchaseOrderDT createFromParcel(Parcel in) {
            return new PurchaseOrderDT(in);
        }

        @Override
        public PurchaseOrderDT[] newArray(int size) {
            return new PurchaseOrderDT[size];
        }
    };

    @SerializedName("qty")
    private int qty;

    @SerializedName("price")
    private double price;

    protected PurchaseOrderDT(Parcel in) {
        super(in);
        Bundle data = in.readBundle(getClass().getClassLoader());
        qty = data.getInt("qty");
        price = data.getDouble("price");
    }

    public PurchaseOrderDT() {
    }

    public PurchaseOrderDT(@NonNull Product product) {
        itemId = product.itemId;
        itemCategory2 = product.itemCategory2;
        itemCode = product.itemCode;
        itemDescription = product.itemDescription;
        itemPrice = product.itemPrice;
        availableQuantity = product.availableQuantity;
        discountPercentage = product.discountPercentage;
        discountValue = product.discountValue;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        super.writeToParcel(dest, flags);
        Bundle data = new Bundle();
        data.putInt("qty", qty);
        data.putDouble("price",price);
        dest.writeBundle(data);
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

Main Activity Code

public class ViewPurchaseOrderActivity extends BaseActivity {

    public static final String ARG_PURCHASE_ORDER = "po";
    private AppCompatEditText txtPoNumber, txtRequestedDate, txtToBeDelivered;
    private RecyclerViewAdapter<PurchaseOrderDT, ViewHolder> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_purchase_order);

        txtPoNumber = findViewById(R.id.txt_po_number);
        txtRequestedDate = findViewById(R.id.txt_requested_date);
        txtToBeDelivered = findViewById(R.id.txt_date);

        RecyclerView list = findViewById(android.R.id.list);
        DividerItemDecoration decoration = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        decoration.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.list_separator));
        list.addItemDecoration(decoration);
        list.setAdapter(adapter = new RecyclerViewAdapter<PurchaseOrderDT, ViewHolder>() {

            @Override
            public void onBindViewHolder(ViewHolder holder, int position, ArrayList<PurchaseOrderDT> mValues) {
                holder.bind(mValues.get(position));
            }

            @NonNull
            @Override
            public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_view_po_item, parent, false);
                return new ViewHolder(view);
            }
        });
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        final PurchaseOrderHD header = getIntent().getParcelableExtra(ARG_PURCHASE_ORDER);
        setTitle("View Purchase Order");
        RestFulWebService.getRestFulWebService().getPurchaseOrderDetail(header.getId()).enqueue(new Callback<ArrayList<PurchaseOrderDT>>() {

            @Override
            public void onResponse(@NonNull Call<ArrayList<PurchaseOrderDT>> call, @NonNull Response<ArrayList<PurchaseOrderDT>> response) {
                ArrayList<PurchaseOrderDT> details;
                if (response.isSuccessful() && (details = response.body()) != null) {
                    txtPoNumber.setText(header.getPoNumber());
                    txtRequestedDate.setText(header.getDate());
                    txtToBeDelivered.setText(header.getRequiredDate());
                    adapter.changeDataSet(details);
                } else {
                    Toast.makeText(getContext(), "Unable to fetch data", Toast.LENGTH_LONG).show();
                }
            }

        });
    }

    private static class ViewHolder extends RecyclerView.ViewHolder {

        private AppCompatEditText txtProductName, txtQuantity, txtPrice;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            txtProductName = itemView.findViewById(R.id.inputDescription);
            txtQuantity = itemView.findViewById(R.id.inputQty);
            txtPrice = itemView.findViewById(R.id.inputPrice);
        }

        void bind(PurchaseOrderDT dt) {
            txtProductName.setText(dt.getItemDescription());
            txtQuantity.setText(String.format(Locale.ENGLISH, "%d", dt.getQty()));
            txtPrice.setText(String.format(Locale.ENGLISH, "%,.2f", dt.getPrice()));

            //getting grand total of item prices

        }
    }
}

2

Answers


  1. I setup the adapter like this:

        public class CitiesAdapter extends RecyclerView.Adapter<CitiesAdapter.ViewHolder> {
            public static ArrayList<City> localDataSet;
            ...
        public CitiesAdapter() {
            //constructor
            localDataSet = new ArrayList<City>();
            ...
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, final int position) {
        City city = localDataSet.get( position );
        ...
    

    In the activity that sets the adapter:

    //code
    cityAdapter = new CitiesAdapter();
    //The data set in the adapter has been initialized at this point.
    //So you can populate it here. CitiesAdapter.localDataSet.add() etc
    cityView.setAdapter( cityAdapter );
    

    If item values change in the adapter, update the data array in the adapter. And thus you can get the total like:

    int totalCities = 0;
    for (City city : CitiesAdapter.localDataSet) {
        totalCities++;
    }
    //totalCities = total.
    

    Otherwise, you can get items via the RecyclerView as well.

    private RecyclerView rvActions; //top of activity class
    rvActions = findViewById(R.id.listedActions); //in OnCreate(). A RecyclerView
    
    RecyclerView.ViewHolder viewHolder = rvActions.findViewHolderForAdapterPosition(position);
    if ( viewHolder != null ) {
        TextView aDesc = viewHolder.itemView.findViewById(R.id.a_desc);
        //getText()?
        viewHolder.itemView.setBackgroundColor(
            ContextCompat.getColor(getApplicationContext(), R.color.white));
    }
    
    Login or Signup to reply.
  2. Try something like this:

    float totAmount=0.0;
      for (int counter = 0; counter < dt.size(); counter++) {             
          totAmount = totAmount + dt.get(counter).price;        
      }     
    

    totAmount will have the value you want

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search