I want the app to automatically compute when the user enters the requested two values into edittext, without needing a button.
Is there a way to do it without using TextWatcher?
here is my attempt. Why doesnt it work? The app force shuts when a number is entered in edittext.
'
public class BodyMassIndex extends Activity
{
double result;
EditText age, height, weight;
TextView tvResult;
int ageInt;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi);
initialize();
TextWatcher textWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
calculate();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
height.addTextChangedListener(textWatcher);
weight.addTextChangedListener(textWatcher);
}
private void initialize() {
// TODO Auto-generated method stub
age = (EditText) findViewById(R.id.etAge);
height = (EditText) findViewById(R.id.etHeight);
weight = (EditText) findViewById(R.id.etWeight);
tvResult = (TextView) findViewById(R.id.tvResult);
}
private void calculate() {
// TODO Auto-generated method stub
double heightInt = 1;
double weightInt = 0;
if (height != null)
heightInt = Double.parseDouble(height.getText().toString());
if (weight != null)
weightInt = Double.parseDouble(weight.getText().toString());
result = weightInt / (heightInt * heightInt);
String textResult = "Your BMI is " + result;
tvResult.setText(textResult);
}}
'