Home > database >  Kotlin App Keeps crashing immediately when running
Kotlin App Keeps crashing immediately when running

Time:08-21

I am very new to programming in general and I have just started coding in Kotlin in Android Studio. I'm trying to build a simple "Check if number is even or odd" app but I'm not sure where I'm going wrong.

My app crashes immediately when I start it up on the emulator.

class MainActivity : AppCompatActivity() {
    private lateinit var enternumber : EditText
    private lateinit var button: Button
    private lateinit var output: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        enternumber = findViewById(R.id.et_number)
        button = findViewById(R.id.btn_click)
        output = findViewById(R.id.tv_output)
        val enternum: Int = enternumber.text.toString().toInt()

        button.setOnClickListener {
            if (enternum % 2 == 0)
                output.text = ("Number is even")
            else
                output.text = ("Number is odd")
        }
    }
}

Any help is greatly appreciated.

CodePudding user response:

First, learn to use the logcat to get helpful exception stacktraces for problem diagnosis. Unfortunately MyApp has stopped. How can I solve this?

One problem here is obvious. Move the

val enternum: Int = enternumber.text.toString().toInt()

inside the onclick listener. At onCreate() phase there's no content in the edittext and toInt() will surely fail. Upon click there might be a number.

CodePudding user response:

Your app keeps crashing due to this: val enternum: Int = enternumber.text.toString().toInt()

You have to create two number vals. One to display as a String, and one to use as an Int in your if statement that is combined with the String.

Here is some code that will accomplish what you are trying to do. I put it into a function just to make it more readable:

class MainActivity : AppCompatActivity() {
private lateinit var enternumber: EditText
private lateinit var button: Button
private lateinit var output: TextView

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

    button = findViewById(R.id.btn_click)
    output = findViewById(R.id.tv_output)

    button.setOnClickListener {
        getEvenOrOdd()
    }

}

fun getEvenOrOdd() {
    enternumber = findViewById(R.id.et_number)
    val displayNumber = enternumber.text.toString()
    val newNum = displayNumber.toInt()
    val even = "Number is even"
    val odd = "Number is odd"
    if (newNum % 2 == 0) {
        output.text = even
    } else {
        output.text = odd
    }

}

}

  • Related