如何从shaver1
获取所有用户ID,然后从musers
获取每个用户的信息?
mDatabaseReference = mDatabase!!.getReference().child("Jobs").child(input_job.selectedItem.toString())
mDatabaseReference!!.addChildEventListener(object:ChildEventListener {
override fun onCancelled(p0: DatabaseError) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onChildMoved(p0: DataSnapshot, p1: String?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onChildChanged(p0: DataSnapshot, p1: String?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onChildAdded(p0: DataSnapshot, p1: String?) {
var userId=p0.getValue().toString()
UserIdsResult.add(userId)
// val map = p0.getValue() as Map<String, Any>
}
答案 0 :(得分:0)
尝试以下操作:
mDatabaseReference = mDatabase!!.getReference().child("Jobs");
mUserReference = mDatabase!!.getReference().child("MUsers");
mDatabaseReference.addValueEventListener(object : ValueEventListener {
override fun onCancelled(error: FirebaseError?) {
println(error!!.message)
}
override fun onDataChange(snapshot: DataSnapshot?) {
val children = snapshot!!.children
children.forEach {
val keys = it.getKey()
val userId = it.child(keys).getValue().toString()
mUserReference.child(userId).addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(error: FirebaseError?) {
println(error!!.message)
}
override fun onDataChange(snapshot: DataSnapshot?) {
val name = snapshot.child("Name").getValue().toString();
}
})
}
}
})
首先添加对子项Jobs
的引用,然后使用forEach
在其内部进行迭代并检索键getKey()
和userIds
。
然后添加对子项MUsers
的引用,并使用child(userId)
并获取数据。
答案 1 :(得分:0)
为了能够在您的Shaver1
节点中获取用户ID,然后获取用户名称,请使用以下代码行:
val rootRef = FirebaseDatabase.getInstance().reference
val shaverRef = rootRef.child("Jobs").child("Shaver1")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (ds in dataSnapshot.children) {
val uid = ds.getValue(String::class.java)
val usersRef = rootRef.child("MUsers").child(uid)
val eventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val name = dataSnapshot.child("Name").getValue(String::class.java)
Log.d(TAG, name)
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d(TAG, databaseError.getMessage()) //Don't ignore errors!
}
}
usersRef.addListenerForSingleValueEvent(eventListener)
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d(TAG, databaseError.getMessage()) //Don't ignore errors!
}
}
shaverRef.addListenerForSingleValueEvent(valueEventListener)