I am developing a simple database application, what I want is to print all the children (names) in one Recycler view, but I don't know how to implement the Kotlin code for that
FOLLOWING IS THE FORMAT OF THE JASON TREE
{
"Head": {
"Jack": {
"Children_Info": {
"Mike": {
"age": "14",
"name": "Mike"
},
"Tike": {
"age": "16",
"name": "Tike"
}
},
"Spouse": {
"name": "Fairy",
"phone_No": "5543"
},
"name": "Jack",
"phone_No": "4321"
},
"Max": {
"Children_Info": {
"Bill": {
"age": "12",
"name": "Bill"
},
"Jill": {
"age": "14",
"name": "Jill"
}
},
"Spouse": {
"name": "marry",
"phone_No": "3346"
},
"name": "Max",
"phone_No": "1234"
}
}
}
My code for DATACLASS
data class data_View(val name : String? = null,
val age : String? = null)
CODE FOR FETCHING DATA
dbref = FirebaseDatabase.getInstance().getReference("Head")**.child("Jack")**.child("Children_Info")
dbref.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if(snapshot.exists()){
for (usersnapshot in snapshot.children){
val user = usersnapshot.getValue(data_View::class.java)
userArrayList.add(user!!)
}
var adapter = AdapterClass(this@MainActivity,userArrayList)
recyclerView.adapter = adapter
adapter.setOnItemClickListener(object : AdapterClass.onItemClickListener{
override fun onItemClick(position: Int) {
Toast.makeText(applicationContext, "YOU CLICKED ON $position", Toast.LENGTH_SHORT).show()
}
})
}
}
In the first line I typed the parent name .child("Jack")
to get children printed in recycler view, but how do I loop through all the parents at once.
But according to my database I need all children to be displayed in my recyclerview ie, mike,tike,bill,jill
It sounds like you want to retrieve the entire Head
node and then loop over the various levels of child nodes in your onDataChange
method:
dbref = FirebaseDatabase.getInstance().getReference("Head")
dbref.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
for (parentSnapshot in snapshot.children) {
// parentSnapshot is Jack or Max, so we'll loop over its Children_Info
for (usersnapshot in parentSnapshot.child("Children_Info").children){
val user = usersnapshot.getValue(data_View::class.java)
userArrayList.add(user!!)
}
}
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.