Muazam
Muazam

Reputation: 379

Empty EditText Android Crash

        @Override
        public void onClick(View view) {
            AtimesB = nrB * nrA;
            try {
                AtimesB = Integer.parseInt(editA.getText().toString());
            }catch(NumberFormatException e){
                textInC.setText("Error!");
                usableInt = false;
                }
            if(AtimesB == Integer.parseInt(editA.getText().toString())){
                editA.setText("");
                textC.setTextColor(Color.parseColor("#87d9ff"));
                textC.append("CORECCT: " + nrB + " x " + nrA + " = " + AtimesB + "\n");
                textInC.setText("");
                nrA = rand.nextInt(50)+1;
                nrB = rand.nextInt(50)+1;
                textA.setText(String.valueOf(nrA));
                textB.setText(String.valueOf(nrB));
            }else if(usableInt = false){
                           textInC.setTextColor(Color.RED);
                           textInC.setText("Error");

            }else{
                textInC.setText("INCORECCT");
            }
        }

Any idea how to fix this? When I click on the button with empty EditText, the application crashes.

Thanks.

Upvotes: 0

Views: 1761

Answers (2)

EboMike
EboMike

Reputation: 77762

Your integer parsing is both inefficient and broken. You're doing the same thing twice. Whenever you write the exact same code twice, you should ask yourself if you're doing it wrong.

Try this:

try {
     if(AtimesB == Integer.parseInt(editA.getText().toString())) {
         editA.setText("");
         textC.setTextColor(Color.parseColor("#87d9ff"));
         textC.append("CORECCT: " + nrB + " x " + nrA + " = " + AtimesB + "\n");
         [...]
     }
} catch(NumberFormatException e){
     textInC.setText("Error!");
     usableInt = false;
}

Also, like I mentioned in a comment, you're missing a = in the comparison (if(usableInt = false).

Upvotes: 0

Rich
Rich

Reputation: 36866

You have one try/catch surrounding a direct call to parseInt on the EditText's text value, but then later on you do it again. This is probably where you're throwing an exception.

Upvotes: 0

Related Questions