I am designing a basic BMI calculator and I have the calculator working, but I need to convert the calculated answer from a TextView which is a double to an integer to enable me right statements with <> operators based on the calculated answer.
How do I convert the answer from the TextView to an integer?
v.findViewById(R.id.bmi).setOnClickListener(this);
return v;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bmi:
try {
EditText w = (EditText) getView().findViewById(R.id.w);
String value = w.getText().toString();
EditText h = (EditText) getView().findViewById(R.id.h);
String value1 = h.getText().toString();
TextView ans = (TextView) getView().findViewById(R.id.ans);
Double l1 = Double.parseDouble(value);
Double l2 = Double.parseDouble(value1);
ans.setText(Double.toString(l1 / (l2 * l2)));
}
catch (Exception e)
{
new AlertDialog.Builder(getActivity()).setNeutralButton("OK",null).setMessage("ALL FIELDS ARE REQUIRED TO COMPUTE YOUR BMI! ").show();
break;
}
}
}
}
First, The conversion is NOT from textview
to int
. textView aint a datatype. If you want the result in int use parseInt()
method. int i = Integer.parseInt(value)
.
[EDIT]
Try this, this will work.
TextView tv = (TextView) findViewById(R.id.tv);
EditText et = (EditText) findViewById(R.id.et);
try {
double d = Double.valueOf(String.valueOf(et.getText()));
tv.setText(String.valueOf( (int) d));
}catch (NumberFormatException e){
Toast.makeText(MainActivity.this, "Enter valid number.", Toast.LENGTH_SHORT).show();
}
I have simplified it for your understanding. The code can still be optimized.