Another Option
How to Total Item Price using volley android studio (ecommerce Cart View)
If the Price
and Qty
values in the JSON object are stored as strings instead of numbers, you will need to convert them to numbers before performing the multiplication operation. Here is an updated version of the code that does this:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_add_to_cart, container, false);
btnOrder = root.findViewById(R.id.btnOrdsssser);
rateview = root.findViewById(R.id.rateview);
}
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, "Your url", null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
double sum = 0;
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
AddToCartModel jCatalogueModel = new AddToCartModel();
jCatalogueModel.setPID(object.getString("PID"));
jCatalogueModel.setPrice(object.getString("Price"));
jCatalogueModel.setPImage(object.getString("PImage"));
jCatalogueModel.setPQnty(object.getString("Qty"));
productModelList.add(jCatalogueModel);
String priceString = object.getString("Price");
double price;
try {
price = Double.parseDouble(priceString);
} catch (NumberFormatException e) {
price = 0;
e.printStackTrace();
}
String quantityString = object.getString("Qty");
int quantity = Integer.parseInt(quantityString);
sum += price * quantity;
} catch (JSONException e) {
e.printStackTrace();
}
}
String sumText = "Total Amount : BDT " + String.format("%.2f", sum);
rateview.setText(sumText);
ProRecycler_addToCart.setLayoutManager(jLinerHorizontalItem);
productAdapter = new AddToCartAdatper (getActivity(),productModelList);
ProRecycler_addToCart.setAdapter(productAdapter);
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(),error.getMessage(),Toast.LENGTH_SHORT);
progressDialog.dismiss();
}
});
}