So I wrote a code saying that if the document of the UserID entered exists, it will return an error.
However,
➀In the code, the dbError variable is returned null instead of being updated.
➁If you use the code in , you will get an error in the return statement.
Where should I improve to return the error?
Code of >
private fundbCheck (userid:String): String?{
vardbError: String?= null
valueb=FirebaseFirestore.getInstance()
val docRef=db.collection("Users").document(userid)
docRef.get().addOnSuccessListener { document->
dbError=if( document.exists()){
US>"ID already in use"
} else {
Null
}
}
return dbError
}
Code 2
private fundbCheck(userid:String){
vardbError: String?= null
valueb=FirebaseFirestore.getInstance()
val docRef=db.collection("Users").document(userid)
docRef.get().addOnSuccessListener { document->
dbError=if( document.exists()){
US>"ID already in use"
} else {
Null
}
return@addOnSuccessListener dbError // This Is the Error
}
}
Listener { document->...
added in docRef.get().addOnSuccessListener
runs asynchronously.
Therefore, for the code of の, return dbError
will be executed immediately after running docRef.get().addOnSuccessListener, so null will be returned.
The workaround is
and so on.
Sample for 1.
private fundbCheck(userid:String, onSuccess:()->Unit, onError:()->Unit){
...
...
if(document.exists()){
onError()
} else {
onSuccess()
}
....
(In this implementation, the method name and the contents of the execution do not match...)
The asynchronous processing of 2 will be a little longer, so I think the following article will be helpful.
https://qiita.com/amay077/items/54deb0de587baae47732
© 2024 OneMinuteCode. All rights reserved.