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



错误为Variable 'uid2' must be initialized,我在它说这句话的地方放了一条注释。我的目标是从一个集合中查询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()是异步的,这意味着在从firestore检索数据之前将执行另一个任务。在您的代码中,哈希映射的创建是在从数据库检索数据之前进行的,因此您会得到uid2未初始化的错误。您可以执行以下操作:

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)
}

另一种方法是使用await(),这将使代码变得非常简单。

这里需要注意的是,Firestore查询是异步的,并且在查询完成之前立即返回。稍后在主线程上调用成功和错误回调,并返回查询结果。

您的代码正在尝试使用uid2,然后在将来的回调中最终会给它一个值。如果要继续处理查询的结果,则处理这些结果的代码必须在回调本身内,而不是在回调之外。

(例外情况是,如果您重写代码以使用协同程序,但这超出了这个问题的范围。(

最新更新