I am making requests to Firebase from android studio, at the moment the POST requests work, but when validating empty fields, the age field causes the app to crash, I need to know how to validate that an editText that receives integers does not remain null or empty anymore That is the problem, for now the other validations are useful. Age is the only integer field in my model.
class FirestoreViewModel: ViewModel() {
val firestoreUseCase = FirestoreUseCase()
fun crearUsuario(nombre:String,apellido:String,edad:Int,sexo:String){
firestoreUseCase.setearUsuarioFirestore(nombre,apellido,edad,sexo)
}
}
//POST function to create user
fun createUser(){
btn_enviardatos.setOnClickListener {
val nombre = etxt_nombre.text.toString().trim()
val apellido = etxt_apellido.text.toString().trim()
val edad = etxt_edad.text.toString().toInt()
val sexo = etxt_sexo.text.toString().trim()
if (nombre.isNotEmpty() && apellido.isNotEmpty() && edad > 0 && sexo.isNotEmpty()){
viewModel.crearUsuario(nombre,apellido,edad,sexo)
etxt_nombre.setText("")
etxt_apellido.setText("")
etxt_edad.setText("")
etxt_sexo.setText("")
}else{
Toast.makeText(this,"Error", Toast.LENGTH_LONG).show()
}
}
}
Avoid the
toInt()
at the beginning and do the following in the validationRemember that the editText cannot be null if you found it with the
findViewById
, and remember that even ifinputType
it is a number, you always receive a string as data, then convert it to what you need, but you have to check that it is not emptyAvoid converting text to Integer directly, instead you can do a try-catch, and in case of error react by changing the result.
Example:
You can also verify that the string is not empty:
Another comment is that you try to change the InputType in the editText if you are programming for android, this way you avoid some surprises about what the user can enter.
The accepted answer is correct but I think it would be better like this:
If the string can be converted to int it will assign it to age if not age equal to 0