Log
:
D/CartActivity-onCreate(18171): onCreate
D/CartActivity-TOTAL-InsideFORLOOP:(18171): 0.0
D/CartActivity-onResume(18171): onResume
D/CartAdapter-TOTAL:(18171): 12.95
正如您在上面的日志中看到的,循环首先在cartactivity中执行,在执行了cartactivity的
onResume()
方法之后,cartadapter正在执行这一行,因此对于我来说,在Total
中cartactivity的For loop
值是0.0。原因不是我要添加到数据arrayList的位置,问题是cartactivity在cartadapter执行之前执行(
where i am getting value for Total
)所以,如果我想在执行cartactivity的
where i am setting value for Total
方法之前调用下面的行,我必须做的是 CartArrayList.cartArraylist.get(position).setTotal(totalPrice);
cartactivity.java:
public class CartActivity extends Activity {
.....
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("CartActivity-onCreate", "onCreate");
setContentView(R.layout.activity_cart);
.......
adapter = new CartAdapter(getApplicationContext(), R.layout.adapter_cart, CartArrayList.cartArraylist);
for (int d = 0; d < CartArrayList.cartArraylist.size(); d++) {
subTotal = subTotal + CartArrayList.cartArraylist.get(d).getTotal();
Log.d("CartActivity-TOTAL-InsideFORLOOP:", String.valueOf(CartArrayList.cartArraylist.get(d).getTotal()));
}
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
textSubTotal.setText(decimalFormat.format(subTotal));
}
@Override
public void onResume() {
super.onResume();
Log.d("CartActivity-onResume", "onResume");
}
}
cartadapter.java:
public class CartAdapter extends BaseAdapter {
.....
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
......
totalPrice = cart.getQuantity() * cart.getPrice();
CartArrayList.cartArraylist.get(position).setTotal(totalPrice);
Log.d("CartAdapter-TOTAL:", String.valueOf(CartArrayList.cartArraylist.get(position).getTotal()));
.....
return convertView;
}
}
最佳答案
在适配器中设置数组列表之前,必须先计算实体中的总值,而不是在getView
中计算。
代码段:
for (int d=0; d<CartArrayList.cartArraylist.size(); d++) {
// calculate total value
Double totalPrice = CartArrayList.cartArraylist.get(d).getQuantity() * CartArrayList.cartArraylist.get(d).getPrice();
CartArrayList.cartArraylist.get(d).setTotal(totalPrice);
// set it for subTotal
subTotal = subTotal + totalPrice;
}
adapter = new CartAdapter(getApplicationContext(), R.layout.adapter_cart, CartArrayList.cartArraylist);
listview.setAdapter(adapter);
希望对你有帮助