Search code examples
androidkotlinandroid-edittextfindviewbyid

App crashes when a button is pressed used for checking user answer


Hello I am trying to create a simple number guesser app where if the number guessed by the user matches with the Random number generator, the textView should output "you have correctly guessed the number" or not but whenever I press the button the program crashes. Please help

The program crashes whenever I press the button.The user should input their number in userAns variable and if the answer is correct. answerCorrect variable should be executed and the text should be displayed and if the number guessed by the user is wrong. answerWrong variable should be executed. I am a beginner so please help

class MainActivity : AppCompatActivity() {
     override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //Calling button method
        val button = findViewById<Button>(R.id.guessBtn)
        //Set on click listener for the button
        button.setOnClickListener {
            buttonPressed()
          }
         }
        //Creating button for button pressed
        private fun buttonPressed() {
            //Method to find view from activity_main
            val result = findViewById<TextView>(R.id.result)
            val userAns = findViewById<EditText>(R.id.answer).toString().toInt()
            //This variable will display the answer
            val answerCorrect = "Congrats, you have correctly guessed the number"
            val answerWrong = "Sorry,you have guessed the wrong number"
            //Making random numbers from 1 to 10
            var randomValues = Random.nextInt(1, 10)
            //Adding a condition to check if user answer matches the random answer
            if(userAns == randomValues){
                result.text = answerCorrect
            }
            else{
                result.text = answerWrong
            }

             }
             }

Solution

  • Without the stack trace, I think I can guess where the crash is occurring from.

    You have the following line inside your buttonPressed method:

        val userAns = findViewById<EditText>(R.id.answer).toString().toInt()
    

    Here you are accessing a view which is an EditText and trying to convert it to a string and then to an integer.

    I think what you mean to do is get the value from your EditText and then convert that to an Integer.

    You can achieve that by doing this:

     val userAnsEditText = findViewById<EditText>(R.id.answer)
     val userAnsText = userAnsEditText.text.toString()
     val userAnsInt = userAnsText.toInt()
    

    This is assuming that you are using the correct id for the EditText.