X
X
xzrist2019-05-24 21:10:00
Java
xzrist, 2019-05-24 21:10:00

Number parsing from EditText does not work, what should I do?

Hello dear site users, I have a problem getting a number from an EditText. When you click on the button, the program crashes. Here is the code:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button btnstart;
    EditText editText;
    Toast toast;
    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        int min = 1;
        int max = 100;
        int first = ThreadLocalRandom.current().nextInt(min, max + 1);
        int second = ThreadLocalRandom.current().nextInt(min, max + 1);
        TextView firstTextView = (TextView) findViewById(R.id.first_text);
        firstTextView.setText("" + first);
        TextView secondView = (TextView) findViewById(R.id.second_text);
        secondView.setText("" + second);
        editText = (EditText) findViewById(R.id.resultText);
        if (TextUtils.isEmpty(editText.getText().toString())) {
            return;
        }
        int res = 0;
        res = Integer.parseInt(editText.getText().toString());
        editText.setText(res);
        btnstart.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int num1 = Integer.parseInt(editText.getText().toString());
        editText.setText(""+num1);
        Toast toast = Toast.makeText(getApplicationContext(),
                num1, Toast.LENGTH_SHORT);
        toast.show();

    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2019-05-24
@xzrist

res = Integer.parseInt(editText.getText().toString());
editText.setText(res);

Of course there is a mistake here. And the Studio probably draws a warning there, saying "hey, the resource ID is expected here, and not some random number there." It's an overload of setText(@StringRes int resourceId);
crashes with ResourceNotFoundException

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question