mercredi 29 avril 2015

Prevent Empty EditText Field

How is it possible to prevent my app from crashing when my EditText field is empty?

    public class Credits extends Activity {
    int inaugural = 1992;
    int differenceInYears;
    int userGuess;
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int output;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_credits);
        final EditText Guess=(EditText)findViewById(R.id.txtYearGuess);
        Button go = (Button)findViewById(R.id.btnCalculate);
        final TextView result = ((TextView)findViewById(R.id.txtResult));

        go.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                int userGuess= Integer.parseInt(Guess.getText().toString());
                differenceInYears = year - inaugural;
                output = userGuess - differenceInYears;

                if (output < -1) {
                    result.setText("Guess again! You guessed too low!");

                    }

                else if (output == 1) {
                    result.setText("You're REALLY close! You guessed too high!");


                    }

                else if (output == -1) {
                    result.setText("You're REALLY close! You guessed too low!");


                    }

                else if (output > 1) {
                    result.setText("Guess again! You guessed too high!");


                    }

                else {
                    result.setText("Good job! You're an FRC Genious!");

                    }



            }

        });
    }

}

Is it as simple as having another if statement watching for an "empty" variable? If so, what would the code for that look like? I'm sort of at a loss for ideas in preventing this crash from happening. If there is any sort of report from Eclipse that could help answer this question, please let me know where to find it.

Thanks!

Aucun commentaire:

Enregistrer un commentaire