I’m new to android development and im having a bit of problem with firebase database. I’m creating a app somewhat similar to e-commerce application.
category1
child1
name: nameOfChild1
value: value
child2
name: nameOfChild2
value: value
child3
This is how my database is structured. im using
dbref = FirebaseDatabase.getInstance().getReference("requiredCategory")
dbref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
for (productSnapshot in snapshot.children) {
val product = productSnapshot.getValue(Product::class.java)
productlist.add(product!!)
}
productrecyclerview.adapter = productAdapter(productlist)
}
}
And Product
class is
data class Product(
var id: String? = null,
var price: String? = null,
)
Instead i would like to change my structure to
category1
child1
nameOfNested1: value
nameOfNested2: value
child2
nameOfNested1: value
nameOfNested2: value
child3
nameOfNested1: Value
nameOfNested2: value
category2
child1
child2
child3
I want to retrive both the key: nameOfNested
and value:value
.How do i go on and change the code get both the id and value?
Thanks in Advance
2
Answers
Let me answer with what i got working and also be a bit more specific about what i was trying to accomplish
First of all, let me start with what i was doing. i had a Firebase Realtime Database that looked like this
(Only an example for demonstration purpose)
I Made a student class that looks like this
I found a snippet online that would retrieve data from db that is given below
It gave a Array that look something like this
As you can see, the structure that i was using was inefficient and i want to change it. Also, instead of a single
Students
refence i wanted to add child which holds the students based on the class they are in. Also i wanted to addage
property to each student as well. So i came up with a structure that looks like thisWhat i was having issue with getting Both the Key and value at the same time. what at the time i was using was
It was not working with what i had.. It was looking for ids
name
andage
. (i renamed theclass
toage
in theStudent
class)I got it working by doing something like this
This works fine and returns a array that i wanted.
I know most of that explanation was unnecessary. i wanted to clarify what my situation was. Also my solution might be the worst. If anyone have a better solution, i'm all ears...
If you also want to get the key of each product, you can do so with: