I use the volley library and load json from the server and display it in recyclerview. I want to create a shopping cart and calculate the total price of the recyclerview items. My problem is that the total cost of the items is not calculated.
Help me please
This is my code:
public class checkout extends AppCompatActivity {
String shop = SHOP;
List<Product6> productList6;
ProductsAdapter6 productsAdapter6;
RecyclerView recyclerView;
private ProductsAdapter6 adapter6;
private GridLayoutManager layoutManager;
RecyclerView.LayoutManager RecyclerViewLayoutManager;
private TextView subTotal;
private double mSubTotal = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkout);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
RecyclerViewLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(RecyclerViewLayoutManager);
adschild2();
productList6 = new ArrayList<>();
subTotal = (TextView) findViewById(R.id.sub_total);
mSubTotal = grandTotal(productList6);
subTotal.setText(String.valueOf(mSubTotal));
}
private int grandTotal(List<Product6> items) {
int totalPrice = 0;
for (int i = 0; i < items.size(); i++) {
totalPrice += items.get(i).getBack();
}
return totalPrice;
}
private void adschild2() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, shop, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
// converting the string to json array object
JSONArray array = new JSONArray(response);
// traversing through all the object
for (int i = 0; i < array.length(); i++) {
// getting product object from json array
JSONObject product6 = array.getJSONObject(i);
// adding the product to product list
productList6.add(new Product6(product6.getInt("id"), product6.getDouble("back")));
}
// creating adapter object and setting it to recyclerview
ProductsAdapter6 adapter6 = new ProductsAdapter6(checkout.this, productList6);
recyclerView.setAdapter(adapter6);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
// adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
}
Your call to
mSubTotal = grandTotal(productList6);
should be inside your call for
adschild2()
in onResponse - after you parsed the JSON.
the reason is that adschild2 is an asynchronous function that populates productList6 only after onResponse is invoked, while the call for grandTotal is synchronous and calculating the sum of an empty list.