I want to get the data objects (address, check_in, check_out) from the date which is in the nested node.
My database goes by like this:
---`attendance` :{
|
|---danielle:{ <---------- here is username, node of `attendance`
| |
| |---2023-04-08: <----------- here is the date she checked in and out for work
| | |
| | |---address: "Thomas street"
| | |
| | |---check_in: "09:02 AM"
| | |
| | |---check_out: "06:30 PM"
| |
| |
| ---2023-04-10":
| |
| |---address: "Maria street"
| |
| |---check_in: "09:02 AM"
| |
| ---check_out: "06:30 PM"
|
---mark:{ <---------- here is another username
|
|---2023-04-07: <----------- here is the date he checked in and out for work
| |
| |---address: "Thomas street"
| |
| |---check_in: "09:02 AM"
| |
| |---check_out: "06:30 PM"
|
|
---2023-04-11":
|
|---address: "Maria street"
|
|---check_in: "10:23 AM"
|
---check_out: "08:30 PM"
I tried to use this coding
val attModel = arrayListOf<AttendanceModel>()
Firebase.database.getReference("Attendance").child("danielle").child("2023-04-08").addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for (h in snapshot.children) {
val data = h.getValue(AttendanceModel::class.java)
attModel.add(data!!)
}
}
}
but i get this error
Android : com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to AttendanceModel
I know danielle
is indeed a String
, but I don’t understand how it can get an error because danielle
has an object node inside.
I also tried this coding here where I tried to nest for the path 2023-04-08
val todays = arrayListOf<AttendanceModel>()
Firebase.database.getReference("Attendance").child("danielle")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for (h in snapshot.children) {
val date = h.child("2023-04-08")
for (i in date.children) {
val dataUser = i.getValue(AttendanceModel::class.java)
todays.add(dataUser!!)
}
In emulator doesnt return anything, and then i tried to log dataUser
, it gives me
DataSnapshot { key = danielle, value = null }
Here is my data class
data class AttendanceModel(
val loc_name: String? = "",
val address: String? = "",
val check_in: String? = "",
val check_out: String? = ""
)
Any kind of help would be so much appreciated!
2
Answers
No need iteration snapshot children because already entire object fetch for date. If we use iteration, it’s will return value for each key which inside the object.
Replace
by
When you attach a listener on the
2023-04-08
, there is no need for an iteration, you can directly read the values of the children, or you can map the node into an object of typeAttendanceModel
. In code, it will be as simple as:The result in the logcat will be: