为什么我的Firebase文档被覆盖?

问题描述 投票:0回答:1

我对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开发和Firestore DB还是陌生的,如果有人可以指出正确的方向,我将不胜感激。我正在创建一个允许用户登录的应用,然后...

android kotlin google-cloud-firestore
1个回答
0
投票

addOnSuccessListener注册一个异步回调。并且checkIfUserExists始终返回false,因为它在从Firebase接收响应(回调执行)之前完成。

© www.soinside.com 2019 - 2024. All rights reserved.