Question

I am a beginner with Android and I'm trying to build an simple app that adds EditTexts' together. I found this example, but it is not working for me. I'm getting an error (on the last line of code) that states "cannot invoke toString() on the primitive double".

What have I done Wrong?

Heres My Code (just Like The Example):

public class MainActivity extends Activity {

private EditText editText1, editText2;
private TextView resultsText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    editText1 = (EditText) findViewById(R.id.editText1);
    editText2 = (EditText) findViewById(R.id.editText2);

    resultsText = (TextView) findViewById(R.id.resultsText);

    TextWatcher textWatcher = new TextWatcher() {
        public void afterTextChanged(Editable s) {
            calculateResult();
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
        }
    };

    editText1.addTextChangedListener(textWatcher);
    editText2.addTextChangedListener(textWatcher);
}

private void calculateResult() throws NumberFormatException {

    Editable editableValue1 = editText1.getText(), 
            editableValue2 = editText2.getText();

            double value1 = 0.0, 
            value2 = 0.0, 
            result;

    if (editableValue1 != null)
        value1 = Double.parseDouble(editableValue1.toString());

    if (editableValue2 != null)
        value1 = Double.parseDouble(editableValue2.toString());

    result = value1 * value2;

    resultsText.setText(result.toString());

}

}

Was it helpful?

Solution 2

Do this resultsText.setText("" + result);

EDIT:

The reason for crash is simple. When you are doing editableValue1 = editText1.getText(); it will return a valid editable, and the text inside that will be an empty string if nothing has been entered into the edit text. So when you are entering a number in one of the edit texts, the associated editable will return a proper double value, but for the other edit text box (for which you have not entered anything yet) will return empty string, so your function calculateResult() will throw NumberFormatException. Since you are not catching that exception, your app will crash. So to make this long story short, just catch the exception when you are calling calculateResult().

public void afterTextChanged(Editable s) {
    try {
        calculateResult();
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
}

OTHER TIPS


You can't call toString on primitives. Use String.valueOf(result) instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top