Using TextWatcher to get values entered to two edittext and multiplying these values without a button. Automatic computation.

StackOverflow https://stackoverflow.com/questions/18091425

  •  23-06-2022
  •  | 
  •  

Domanda

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);




}}
'
È stato utile?

Soluzione

You should set the default values of the edittext to 0. Its probably force closing because you are trying to parse an empty string from an edittext that has nothing in it;

EDIT: try this

if (height != null)
    heightInt = Double.parseDouble(!height.getText().toString().equals("")?
           height.getText().toString() : "0");

if (weight != null)
    weightInt = Double.parseDouble(!weight.getText().toString().equals("")?
           weight.getText().toString() : "0");

this way your using a condition where no matter what youll be parsing a value that wont throw an exception

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top