Log
says:
D/CartActivity-onCreate(18171): onCreate
D/CartActivity-TOTAL-InsideFORLOOP:(18171): 0.0
D/CartActivity-onResume(18171): onResume
D/CartAdapter-TOTAL:(18171): 12.95
As you can see in above Log for loop is executed first in CartActivity and after the execution of onResume()
method of CartActivity, CartAdapter is executing this line, therefore for i am getting 0.0 as value of Total
in CartActivity inside For loop
The reason is not where i am adding to data ArrayList, issue is CartActivity executes (where i am getting value for Total
) before CartAdapter execution (where i am setting value for Total
)
So what I have to do, If I would like to call below line before execution of onCreate()
method of CartActivity
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;
}
}
You have to calculate Total value in entity only before setting the array list in Adapter, rather than calculating it in 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);
Hope it helps ツ
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With