Reputation: 598
I would like to change a TextView as a user adds things to a cart. The initial value is 0.00 and as the user adds items, this is added to the value. I have an AlertDialog that pops up when clicking a button that allows the user to choose an item.
My issue is a java.lang.StringToReal.invalidReal error. I think that I may not be getting the value of the TextVeiw properly but am not totally sure.
Thanks to anyone looking at this.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.pickItem);
builder.setItems(R.array.items, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
CartItems ci = new CartItems();
ci.setItem(which);
ci.setPrice(which);
cart.add(ci);
totalPriceTV = (TextView)findViewById(R.id.textView2);
double totalPrice = Double.parseDouble(totalPriceTV.toString());
totalPrice += ci.getPrice();
String newTotal = new Double(totalPrice).toString();
totalPriceTV.setText(newTotal);
}
});
builder.create();
builder.show();
}
});
}
Upvotes: 1
Views: 257
Reputation: 2840
In order to change the text of a TextView
in Android just use the ordinary geters and setters:
TextView.getText();
TextView.setText("text");
Since you deal with numbers i suggest you to use DecimalFormat
when parsing a double to string. You can easily define the format of the number (i.e the number of digits after comma or the separator characters)
DecimalFormat df = new DecimalFormat("###,###.00");
String price = df.parse(someDouble);
textView.setText(price);
For these numbers: 234123.2341234 12.341123
the DecimalFormat
would give you the following result:
234,123.23
and 12.34
Upvotes: 2
Reputation: 5056
Just use totalPriceTV.setText(""+totalPrice);
or
totalPriceTV.setText(String.valueOf(totalPrice));
Upvotes: 1
Reputation: 291
Taken from page: http://developer.android.com/reference/android/view/View.html#toString()
Added in API level 1 Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:
getClass().getName() + '@' + Integer.toHexString(hashCode())
As a result you should use getText();
ie:
totalPriceTV.getText()
Upvotes: 1
Reputation: 3393
In this line
double totalPrice = Double.parseDouble(totalPriceTV.toString());
Change totalPriceTV.toString()
to totalPriceTV.getText().toString()
and try again.
Upvotes: 3