我使用 volley 庫并從服務器加載 json 并將其顯示在 recyclerview 中。我想創建一個購物車并計算 recyclerview 項目的總價。我的問題是沒有計算物品的總成本。請幫幫我這是我的代碼: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>()
2 回答

aluckdog
TA貢獻1847條經驗 獲得超7個贊
您的來電
mSubTotal = grandTotal(productList6);
應該在你的呼吁中
adschild2()
在 onResponse - 解析 JSON 之后。
原因是 adschild2 是一個異步函數,它只有在 onResponse 被調用后才填充 productList6,而對 grandTotal 的調用是同步的,并計算空列表的總和。
添加回答
舉報
0/150
提交
取消