我对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开发最佳实践的正确方向,我将不胜感激!