I am making a login, but I would like to validate so that something can be done when the user does not exist or the password doesn't match. But I always get "[]" in the body and I do not know how to set that in an "if".
I tried if(response)
, if(response!=null)
and more but nothing worked. It always catches it like "not null".
var post: List<UserData>?
val response: Call<List<UserData>> = service.userLogin(email, pass)
response.enqueue(object : Callback<List<UserData>> {
override fun onResponse(call: Call<List<UserData>>, response: Response<List<UserData>>) {
post = response?.body()
println(post)
CodePudding user response:
If you are sure that you always get the response is "[]" in the body, it means that the response is not null, just an empty array even if the user is not existing or the pass is wrong.
Regards your code, I change a little bit:
override fun onResponse(call: Call<List<UserData>>, response: Response<List<UserData>>) {
post = when (response.body().isNotEmpty()) {
true -> response.body()
false -> listOf<UserData>() // or null, because `post` is nullable
}
println(post)
}
There are 3 methods to judge a list is empty/null
CodePudding user response:
override fun onResponse(call: Call<List<UserData>>, response: Response<List<UserData>>) {
if (response.body()?.isEmpty() == true) {
println("Empty")
} else {
println("No empty")
}
}
With the help of the comment of down below I got the solution, thanks.