Home > Software design >  Kotlin Edit Text as Integer
Kotlin Edit Text as Integer

Time:12-27

I want to make an app where you have to guess two numbers that eaquals a random number. But my app crash at the start because of java.lang.NumberFormatException: For input string: ""

val intNumber1 = etNumber1.text.toString().toInt() is the line that causes the crash. But I dont know what to do.

Here is my main activity:

//Buttons und Text initialisieren
private lateinit var btnCheck: Button
private lateinit var tvRndNumber: TextView
private lateinit var etNumber1: EditText
private lateinit var etNumber2: EditText



override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)



    //Buttons und Text verknüpfen
    btnCheck = findViewById(R.id.checkButton)
    tvRndNumber = findViewById(R.id.randomNumber)
    etNumber1 = findViewById(R.id.inputNumber1)
    etNumber2 = findViewById(R.id.inputNumber2)



    val intNumber1 = etNumber1.text.toString().toInt()
    val intNumber2 = etNumber2.text.toString().toInt()



    fun getRandomNumber(): Int {
        return Random.nextInt(0,100)
    }



    var intRdnNumber = getRandomNumber()
    tvRndNumber.text = intRdnNumber.toString()



    fun checkNumbers(num1: Int, num2: Int){

        if (num1   num2 == intRdnNumber) {
            tvRndNumber.text = "Richtig"
        }
        else {
            Toast.makeText(this,"Probier es nochmal", Toast.LENGTH_LONG).show()
        }
    }



    btnCheck.setOnClickListener {
        checkNumbers(intNumber1, intNumber2)
    }

CodePudding user response:

Try like the following

//....
 val intNumber1 = etNumber1.text.toString()
 val intNumber2 = etNumber2.text.toString()

//.....
btnCheck.setOnClickListener {
    if(intNumber1.isNotEmpty && intNumber2.isNotEmpty{
        checkNumbers(intNumber1.toInt(), intNumber2.toInt())
    }else{
        // input filed is empty
        // show message or do nothing
    }
    
}

CodePudding user response:

 val intNumber1 = if(etNumber1.text.isNotEmpty()) {
       etNumber1.text.toString().toInt()
    } else {
       0
    }

     val intNumber2 = if(etNumber2.text.isNotEmpty()) {
        etNumber2.text.toString().toInt()
    } else {
        0
    }
  • Related