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
- The lines where you are retrieving the
selectedItem
. You can handle those by adding the?
operator after the spinner instances - The line where you convert
value
to aDouble. You can avoid the error by using
toDoubleOrNulland providing a default value in case that
value` is not numeric - The line where you set the
text
ofcurrencyConverted
. 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()
}