我对Android开发和Firestore DB还是比较陌生,如果有人可以向我指出正确的方向,我将不胜感激。
我正在创建一个允许用户登录的应用程序,并且将他们的电子邮件用作“用户”集合中文档的主要标识符。我希望能够使用他们的电子邮件检查用户是否已经存在,如果确实存在,则返回该电子邮件已经注册了一个帐户。
到目前为止,我设法将用户数据输入数据库并查询数据库以检查用户是否存在。
但是,我的代码用提供的电子邮件覆盖了用户,而不是忽略写请求并警告用户该电子邮件已经存在。
我已经尝试创建一个私有帮助器布尔函数,该函数将调用“ checkIfUserExists()”,该函数包含一个emailFlag来查询数据库并将标志更改为true(如果存在)并返回标志的状态,我将在其中处理调用根据checkIfUserExists()的结果写入数据库
//Set on click listener to call Write To DB function
//This is where my writetoDb and checkIfUserExist come together inside my onCreate Method
submitButton.setOnClickListener {
//Check to make sure there are no users registered with that email
if (!checkIfUserExists())
writeUserToDb()
else
Toast.makeText(
this,
"Account already registered with supplied email, choose another.",
Toast.LENGTH_LONG
).show()
}
//This should be called if and only if checkIfUserExists returns false
@SuppressLint("NewApi")
private fun writeUserToDb() {
//User Privilege is initially set to 0
val user = hashMapOf(
"firstName" to firstName.text.toString(),
"lastName" to lastName.text.toString(),
"email" to email.text.toString(),
"password" to password.text.toString(),
"birthDate" to SimpleDateFormat("dd-MM-yyyy", Locale.US).parse(date.text.toString()),
"userPrivilege" to 0,
"userComments" to listOf("")
)
//Create a new document for the User with the ID as Email of user
//useful to query db and check if user already exists
try {
db.collection("users").document(email.text.toString()).set(user).addOnSuccessListener {
Log.d(
TAG,
"DocumentSnapshot added with ID as Email: $email"
)
}.addOnFailureListener { e -> Log.w(TAG, "Error adding document", e) }
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun checkIfUserExists(): Boolean {
var emailFlagExist = false
val userExistQuery = db.collection("users")
userExistQuery.document(email.text.toString()).get()
.addOnSuccessListener { document ->
if (document != null)
Log.w(
TAG,
"Account already exists with supplied email : ${email.text}"
)
emailFlagExist = true
}
return emailFlagExist
//TODO can create a toast to alert user if account is already registered with this email
}
现在,它提醒我它在数据库中检测到具有给定电子邮件的用户,但是在我单击注册页面中的“提交”按钮之后,它也用最近提供的信息覆盖了当前用户。
我该如何防止这种情况的发生,如果您也能为我指出FireStore / Android开发最佳实践的正确方向,我将不胜感激!
在addOnSuccessListener
注册一个异步回调。并且checkIfUserExists
始终返回false,因为它在接收到来自Firebase的响应(回调执行)之前完成。
解决此问题的一种方法是将逻辑放在回调中(在回调方法中调用writeUserToDb)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句