【发布时间】:2020-03-06 02:08:12
【问题描述】:
我对 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 开发最佳实践的正确方向,我将不胜感激!
【问题讨论】:
标签: android kotlin google-cloud-firestore