V
V
Vasya Nikolaev2017-07-13 18:06:36
Java
Vasya Nikolaev, 2017-07-13 18:06:36

Why does an Android app crash with an error?

public class MainActivity extends AppCompatActivity {
    TextView Discr;
    EditText b;
    Double x;
    Double d;
    Integer z;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Discr = (TextView) findViewById(R.id.d);
     b = (EditText) findViewById(R.id.b);
     z = Integer.parseInt(b.getText().toString()); ****
     d = Math.pow(z,2);
     Discr.setText(d.toString());

    }

When launched on the emulator crashes: Unfortunately App was stopped. If you remove the line marked **** and replace z with a number in the next line, then everything works. That is, there is a problem in parseInt, what am I doing wrong? In fact, you need to take the value from the EditText, and use it to calculate a certain value, in this case, to square the number from the b field.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri, 2017-07-14
@YuryBorodkin

it is obvious that the int cannot be parsed, the edittext is empty / there is not a number.
b.addTextChangedListener
(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
Integer integer = null;
try {
integer = Integer.parseInt(s.toString());
Discr.setText(integer.toString());
} catch (NumberFormatException ignored) {
}
}
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question