简体   繁体   English

为什么我会收到有关变量初始化的错误?

[英]Why am I getting this error about variable initialization?

The error is Variable 'uid2' must be initialized and I've put a comment where it's saying this.错误是Variable 'uid2' must be initialized ,我已经在它说这个的地方发表了评论。 My goal is to query a uid from one collection and then insert it into another collection.我的目标是从一个集合中查询一个 uid,然后将其插入到另一个集合中。

fun addFriend(username: String) { 

        var uid2: String

        var docRef = firebaseFirestore.collection(collUsers).whereEqualTo("username", username)
            .get()
            .addOnSuccessListener { documents ->
                for (document in documents) {
                    Log.d(tag, "${document.id} => ${document.data}")
                    uid2 = document.data.getValue("uid").toString()
                    Log.d(tag, "uid_2: $uid2")
                }
            }
            .addOnFailureListener { exception ->
                Log.w(tag, "Error getting documents: ", exception)
            }

        var collRelationships2: CollectionReference = firebaseFirestore.collection(collRelationships)
        var relationshipsMap: HashMap<String, Any> = hashMapOf(
                                        "uid_1" to firebaseAuth.uid.toString()
                                        , "uid_2" to uid2 //Error is here
                                        , "stat" to 1
                                        , "createDate" to FieldValue.serverTimestamp()
                                        , "modifiedDate" to FieldValue.serverTimestamp()
                                    )

        collRelationships2.add(relationshipsMap)

    }

get() is asynchronous, which means that another task will be executed before even retrieving the data from firestore. get()是异步的,这意味着在从 firestore 检索数据之前将执行另一个任务。 In your code, the creation of the hash map is happening before retrieving the data from the database, therefore you get the error that uid2 is not initialized.在您的代码中,hash map 的创建是在从数据库中检索数据之前发生的,因此您会收到未初始化uid2的错误。 You can do the following:您可以执行以下操作:

        var docRef = firebaseFirestore.collection(collUsers).whereEqualTo("username", username)
            .get()
            .addOnSuccessListener { documents ->
                for (document in documents) {
                    Log.d(tag, "${document.id} => ${document.data}")
                    uid2 = document.data.getValue("uid").toString()
                    Log.d(tag, "uid_2: $uid2")

                var collRelationships2: CollectionReference = firebaseFirestore.collection(collRelationships)
                var relationshipsMap: HashMap<String, Any> = hashMapOf(
                                        "uid_1" to firebaseAuth.uid.toString()
                                        , "uid_2" to uid2 //Error is here
                                        , "stat" to 1
                                        , "createDate" to FieldValue.serverTimestamp()
                                        , "modifiedDate" to FieldValue.serverTimestamp()
                                    )

        collRelationships2.add(relationshipsMap)
                }
            }
            .addOnFailureListener { exception ->
                Log.w(tag, "Error getting documents: ", exception)
            }

Another way is to use await() which will make the code very simple.另一种方法是使用await() ,这将使代码非常简单。

The thing to be aware of here is that Firestore queries are asynchronous, and return immediately before the query is complete.这里要注意的是 Firestore 查询是异步的,并且会在查询完成之前立即返回。 The success and error callbacks are invoked some time later on the main thread with the results of the query.稍后在主线程上使用查询结果调用成功和错误回调。

Your code is attempting to use uid2 before it will eventually be given a value in the future callback.您的代码正在尝试使用uid2 ,然后它最终会在未来的回调中被赋予一个值。 If you want to continue work with the results of the query, the code to work with those results must be within the callback itself, not outside the callback.如果要继续处理查询结果,处理这些结果的代码必须在回调本身内,而不是在回调外。

(The exception is if you rewrite your code to use coroutines, but that's outside the scope of this question.) (例外情况是,如果您重写代码以使用协程,但这不在此问题的 scope 范围内。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM