Home > Software engineering >  How can I make Spinner function stop crashing my app when trying to get the selected item?
How can I make Spinner function stop crashing my app when trying to get the selected item?

Time:03-29

I'm having Trouble getting string values from a spinner without it crashing my app , I want to make a choice according to the 2 pair of selected items in the when Function

val convertFrom = spnConvertFrom.selectedItem.toString()
val convertTo = spnConvertTo.selectedItem.toString()
val value = initialAmount.toString()
var valor2= value.toDouble()
when {
    //Condicion
    (convertFrom.equals("NIO") && convertTo.equals("USD")) -> currencyConverted.apply {
        text = "Something"
    }
    else -> Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show()
}

I've tried to switch the syntax a bit from = to .equals() (Same thing) Read something about it being null at the moment of the comparison but have no idea how to check it , I'm quite new to Kotlin and programing in android

CodePudding user response:

There are several lines which could case an NPE

  1. The lines where you are retrieving the selectedItem. You can handle those by adding the ? operator after the spinner instances
  2. The line where you convert value to a Double. You can avoid the error by using toDoubleOrNulland providing a default value in case thatvalue` is not numeric
  3. The line where you set the text of currencyConverted. If it is optional you should add the ? operator there as well:
 val convertFrom = spnConvertFrom?.selectedItem.toString()
 val convertTo = spnConvertTo?.selectedItem.toString()
 val value = initialAmount.toString()
 var valor2 = value.toDoubleOrNull() ?: 0.0

when {
    //Condicion
    (convertFrom.equals("NIO") && convertTo.equals("USD")) -> currencyConverted?.text = "Something"
    else -> Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show()
}
  • Related