Home > OS >  String to Int or Double conversion function crashes my app
String to Int or Double conversion function crashes my app

Time:01-27

I am creating an App, and I have such a problem. This function reads string from TextView, splits it on the operator, then converts these things to Int, and calculates them. When I call this function, the app crashes. Everything works fine if I delete these two "toInt()" lines - but it does not make the job it's supposed to do. How to solve it?

Here's the code:

fun onEqual(operator: String){
    //if(lastNumeric){
        onDigit(16)
        onOperator(16)
        var txtValue = displayResult.text.toString()
        var splitValue = txtValue.split(operator)
        var firstValue = splitValue[0]
        var secValue = splitValue[1]
        var frst = firstValue.toInt() //if i delete these two lines, app does not crash
        var sec = secValue.toInt() //if i delete these two lines, app does not crash

        //displayResult.setText(result.toString())
}

Thanks for any help!!!

I tried setting the operator variable to null, changing these two lines from toInt() to toDouble(), and also changing names of the variables - none of these solutions worked.

CodePudding user response:

In the documentation of toInt method, you can read that when that method can't convert a given string to Int it throws an exception. However, String has also a method toIntOrNull that in that case returns null instead of throwing an exception. If you don't want to have a crash you can use that method but you instead must check if your variables first and sec are not null.

  • Related