This is inside my Response.Listener on my StringRequest.
这是我的StringRequest上的Response.Listener内部。
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("cart");
for (int i = 0; i<array.length(); i++){
JSONObject o = array.getJSONObject(i);
CartItem item = new CartItem(
o.getString("cardno"),
o.getString("product_id"),
o.getString("name"),
o.getString("quantity"),
o.getString("price"),
o.getString("category")
);
cartItems.add(item);
}
adapter = new CartAdaptor(cartItems, getContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
It will get the JSON Array and put it in my CartItem.java and will populate my CartAdaptor.java
它将获取JSON数组并将其放入我的CartItem.java中并填充我的CartAdaptor.java
public CartItem(String cardno, String product_id, String name, String quantity, String price, String category) {
this.cardno = cardno;
this.product_id = product_id;
this.name = name;
this.quantity = quantity;
this.price = price;
this.category = category;
How can I total all the price in that array?
我如何计算该阵列中的所有价格?
1 个解决方案
#1
1
I'm not sure where you want to get total price.
我不确定你想要在哪里得到总价。
And I suggest one.
我建议一个。
try {
int total = 0; // add this
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("cart");
for (int i = 0; i<array.length(); i++){
JSONObject o = array.getJSONObject(i);
CartItem item = new CartItem(
o.getString("cardno"),
o.getString("product_id"),
o.getString("name"),
o.getString("quantity"),
o.getString("price"),
o.getString("category")
);
cartItems.add(item);
// add this
if(o.getString("price") != null &&
o.getString("price") != "" ){
total += Integer.parseInt(o.getString("price"));
}
}
adapter = new CartAdaptor(cartItems, getContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
then you can get total prices.
那么你可以得到总价。
#1
1
I'm not sure where you want to get total price.
我不确定你想要在哪里得到总价。
And I suggest one.
我建议一个。
try {
int total = 0; // add this
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("cart");
for (int i = 0; i<array.length(); i++){
JSONObject o = array.getJSONObject(i);
CartItem item = new CartItem(
o.getString("cardno"),
o.getString("product_id"),
o.getString("name"),
o.getString("quantity"),
o.getString("price"),
o.getString("category")
);
cartItems.add(item);
// add this
if(o.getString("price") != null &&
o.getString("price") != "" ){
total += Integer.parseInt(o.getString("price"));
}
}
adapter = new CartAdaptor(cartItems, getContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
then you can get total prices.
那么你可以得到总价。