显示Firebase中的目标数据 [英] Display target data from firebase
问题描述
我在fragmentA
中显示我的目标列表,当我单击其中一个目标时,我将该目标的向导传递给fragmentB
I display a list of my targets in fragmentA
, when I click on one of them, I pass the guid of this target to the fragmentB
之后,我尝试在fragmentB
中为此GUId显示此目标的数据:
After that, I try in the fragmentB
display the data of this target for this guid:
private fun fetchTarget(guid: String) {
val uid = firebaseUser!!.uid
// Attach a listener to read the data at the target id
databaseReference?.child("targets")?.child("users")
?.child(uid)?.child("targets")?.child(guid)?.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val data = dataSnapshot.value as? HashMap<String, String>?
val name = data?.get("name") ?: ""
val description = data?.get("description") ?: ""
if (name.isEmpty()) Log.d("some", "nameIsEmpty")
else updateViewsContent(name = name, description = description)
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("some", databaseError.message)
}
})
}
在这里,我得到了指导:-LmfEVnwgqCUqt7beHDg
在我的控制台中,我有下一个结构:
Here I get the guid: -LmfEVnwgqCUqt7beHDg
And in my console i have next structure:
不幸的是,尽管像我安装的所有链条一样,我无法显示目标的数据
Unfortunately I can't display data of target, though like all the chains I installed
问:我如何下载-LmfEVnx-y7c3oh8_U9F
?
推荐答案
要显示属于单个guid
的数据,您应该使用查询,然后像下面的几行一样遍历DataSnapshot
对象.代码:
To display the data that belongs to a single guid
, you should use a query and then iterate through the DataSnapshot
object like in the following lines of code:
val uid = FirebaseAuth.getInstance().currentUser!!.uid
val rootRef = FirebaseDatabase.getInstance().reference
val targetsRef = rootRef!!.child("targets").child("users").child(uid).child("targets")
val query = targetsRef.orderByChild("guid").equalTo("-LmfEVnwgqCUqt7beHDg")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (ds in dataSnapshot.children) {
val target = ds.getValue(Target::class.java)
Log.d(TAG, target.name)
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d(TAG, databaseError.getMessage()) //Don't ignore errors!
}
}
query.addListenerForSingleValueEvent(valueEventListener)
logcat中的结果将是:
The result in the logcat will be:
fgg
这篇关于显示Firebase中的目标数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!