Saffa
Saffa

Reputation: 73

Why does my app crash when i try to populate a TextView with an integer value?

I'm trying to develop an app that compares the user's input number to a randomly generated number from the computer, depending on whether the input number is higher, lower or the same as the generated number, there is a different message output. However the app crashes (with this stacktrace) whenever I try and run it. Here is my code for my method:

If anyone can recognise why it's crashing it would be great - new to Android so it's hard to see errors.

public void guessingGame (View v)
{
    EditText guess = (EditText) findViewById(R.id.ETguess);
    TextView guessError = (TextView) findViewById(R.id.guessError);
    TextView compGuess = (TextView) findViewById(R.id.tvCompGuess);

    int guessValue = Integer.parseInt(guess.getText().toString());

    if (guessValue > 20)
    {
        guessError.setVisibility(View.VISIBLE);
        guess.getText().clear();
    }
    else if (guessValue < 1)
    {
        guessError.setVisibility(View.VISIBLE);
        guess.getText().clear();
    }
    else 
    {
        int min = 1;
        int max = 20;

        Random r = new Random();
        int i = r.nextInt(max - min + 1) + min;

        int computerNumber = i;
        compGuess.setText(i);

        if (computerNumber > guessValue)
        {
            guessError.setText("Too low!");
        }
        else if (computerNumber < guessValue)
        {
            guessError.setText("Too high!");
        }
        else if (computerNumber == guessValue)
        {
            guessError.setText("Good Guess!");
        }
    }

}

Upvotes: 0

Views: 123

Answers (1)

Jherico
Jherico

Reputation: 29240

    compGuess.setText(i);

You cannot use TextView.setText(int) to set the text to an arbitrary integer. The integer must be the resource ID of a string (typically defined in res/values/strings.xml, or imported from one of your upstream dependencies).

If you want to set a TextView's contents to a string representing an integer you should do it like this

    compGuess.setText(Integer.toString(i));

Upvotes: 1

Related Questions