Solution 1 :
rawScore
is an EditText
so you can’t cast it to Double with as
since they’re not in the same class hierarchy. You have to use the text
property to get the text the user has typed. Then you can safely convert the text to a Double
using toDoubleOrNull()
. It will return null
if the String is invalid to convert to a Double
.
private fun calculateMdl(rawScore: EditText) {
val key = rawScore.text.toDoubleOrNull()
if (scoreModel.eventMDL.containsKey(key)) {
newAcft_textView_mdl.text = key.toString()
}
}
Problem :
I am coming from Swift and I am trying to understand Kotlin.
-
In iOS I had a picker that displayed the keys and stored the values in a @State object
-
How can I use the EditText to do the same thing but avoid the user entered errors?
-
Could this conditional statement be an Enum in Kotlin for the other scoreModel maps/Dictionaries?
class NewAcftActivity : AppCompatActivity() {
implemented the model like this, not sure id this is Kotlin protocol.
private val scoreModel = ScoreModel()
private lateinit var textEditMdl: EditText
ignore the rest of these TextEdit views if the first view answers the rest of the problem
private lateinit var textEditSpt: EditText
private lateinit var textEditHrp: EditText
private lateinit var textEditSdc: EditText
private lateinit var textEditLtk: EditText
private lateinit var textEditTmr: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new_acft)
textEditMdl = findViewById(R.id.newAcft_textEdit_mdl)
Other text edits…
textEditSpt = findViewById(R.id.newAcft_textEdit_spt)
textEditHrp = findViewById(R.id.newAcft_textEdit_hrp)
textEditSdc = findViewById(R.id.newAcft_textEdit_sdc)
textEditLtk = findViewById(R.id.newAcft_textEdit_ltk)
textEditTmr = findViewById(R.id.newAcft_textEdit_tmr)
newAcft_btn_save.setOnClickListener {
calculateMdl(textEditMdl)
}
}
Ran into problems here… Not sure how to evaluate the map collection properly.
private fun calculateMdl(rawScore: EditText) {
var key = rawScore
if (scoreModel.eventMDL.containsKey(key as Double)) {
newAcft_textView_mdl.text = key.toString()
}
}
}
model. this only applies to the first TextEdit but is generally the same for each event
class ScoreModel {
val eventMDL = mapOf(
340.0 to 100.0,
330.0 to 97.0,
320.0 to 94.0,
310.0 to 92.0,
300.0 to 90.0,
290.0 to 88.0,
280.0 to 86.0,
270.0 to 84.0,
260.0 to 82.0,
250.0 to 80.0,
240.0 to 78.0,
230.0 to 76.0,
220.0 to 74.0,
210.0 to 72.0,
200.0 to 70.0,
190.0 to 68.0,
180.0 to 65.0,
170.0 to 64.0,
160.0 to 63.0,
150.0 to 62.0,
140.0 to 60.0,
130.0 to 50.0,
120.0 to 40.0,
110.0 to 30.0,
100.0 to 20.0,
90.0 to 10.0,
80.0 to 0.0,
0.0 to 0.0)
}
Comments
Comment posted by cbear84
just had to make rawScore into a variable and it worked just fine