so I have this problem where I am trying to make Random Number Generator app on android. Basically you set the minimum and the maximum number and then it randomly picks numbers between min and max. However my problem comes if the min or max TextEdit field is empty, the app crashes. I would like to display "X" on the screen. How to check if the field is empty or not? I am using kotlin and here is sample of my code. I am begginer so please do not flame me if the code is wrong :)
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rollButton = findViewById<Button>(R.id.rollButton)
val resultsTextView = findViewById<TextView>(R.id.resultsTextView)
//val seekBar = findViewById<SeekBar>(R.id.seekBar)
val min = findViewById<TextView>(R.id.number_min)
val max = findViewById<TextView>(R.id.number_max)
rollButton.setOnClickListener {
if(min.text.toString().toInt()>= 0 && max.text.toString().toInt() <= 1000){
val rand = Random.nextInt(min.text.toString().toInt(),max.text.toString().toInt()+1)
resultsTextView.text = rand.toString()
}
else if(min.text.toString().isNullOrBlank()){
resultsTextView.text = "X"
}
else{
resultsTextView.text = "X"
}
}
}
}
To check if your EditText is empty use isNullOrEmpty()
. This will check if your field is empty or is null, like the method name says. Here is an example:
val editTextString :String = editText.text.toString()
if(!editTextString.isNullOrEmpty()) //returns true if string is null or empty
There is another approach with TextUtils
but since you are using Kotlin
this approach is better.
EDIT:
You are doing this:
if(min.text.toString().toInt()>= 0 && max.text.toString().toInt() <= 1000){
val rand = Random.nextInt(min.text.toString().toInt(),max.text.toString().toInt()+1)
resultsTextView.text = rand.toString()
}
and here this line min.text.toString().toInt()
is throwing you an exception. The reason for this is because currently min
or max
are empty String
. So compailer can't format number from an String equals to ""
. You should do it like this:
if(!min.text.toString().isNullOrEmpty() && !max.text.toString().isNullOrEmpty() && min.text.toString().toInt()>= 0 && max.text.toString().toInt() <= 1000){
val rand = Random.nextInt(min.text.toString().toInt(),max.text.toString().toInt()+1)
resultsTextView.text = rand.toString()
}
I hope this works. If not, then take this into two IF statements like this:
if(min.text.toString().isNullOrEmpty() || max.text.toString().isNullOrEmpty() {
resultsTextView.text = "X"
} else if(min.text.toString().toInt() >= 0 && max.text.toString().toInt() <= 1000) {
val rand = Random.nextInt(min.text.toString().toInt(), max.text.toString.toInt()+1)
resultsTextView.text = rand.toString()
}
The second approach is maybe an even better and cleaner version since you don't have to check for anything else later.