I'm developing a server side app using Kotlin for managing my list of web customers in Firebase. I've successfully added the Java Firebase Admin SDK to my Kotlin and have gotten a functional connection with my Realtime Database.
However, I just noticed one problem. I added a ChildEventListener for listening to changes to their data, and it works nice on every customer but the first one in the list. No matter if I order the data or no with "orderBy", the first queried item never receives a ChildChanged callback when actually edited in the database.
var ref=FirebaseDatabase.getInstance().getReference("web-
customers").orderByChild("displayName")
ref.addChildEventListener(object:ChildEventListener{
override fun onCancelled(p0: DatabaseError?) {
if(p0!=null)
println(p0.message)
}
override fun onChildMoved(p0: DataSnapshot?, p1: String?) {
println("A child moved !!!!!!!!!!!!!!!!!!")
}
override fun onChildChanged(p0: DataSnapshot, p1: String) {
println("A child changed !!!!!!!!!!!!!!!!!!")
val key=p0.key as String
println("A customer changed: "+key)
for(value:HashMap<String,Any> in list){
println(value.get(".key") as String+": "+value.get("displayName") as String)
if((value.get(".key") as String).equals(key)){
val valor=p0.value as HashMap<String,Any>
for(llave in valor.keys){
val dato=valor.get(llave) as Any
value.put(llave,dato)
}
println("Customer "+valor.get("displayName") as String+" modified!!!!!!")
refresh()
break
}
}
}
override fun onChildAdded(p0: DataSnapshot, p1: String?) {
println("A child added !!!!!!!!!!!!!!!!!!")
val value=p0.value as HashMap<String,Any>
value.put(".key",p0.key as String)
list.add(value)
}
override fun onChildRemoved(p0: DataSnapshot?) {
println("A child removed !!!!!!!!!!!!!!!!!!")
}
})
I thought there could be some problem with the data in my customers, so it crashed without even throwing an exception, but even after adding a single println for checking a ChildChanged callback was fired, it doesn't do a thing with the first customer in the list!
I've done a similar code in the past for Java (without Kotlin) and they always worked great.
I'm using latest Firebase Java SDK version, 5.2.0.
Has anyone experienced a similar error?
Thanks to a comment by @Alex Mamo, I addressed my attention to the previousChildName params, and there was the problem that had me trapped for hours!
Given Kotlin's default's behavior about not allowing Non-null references in variables without a "?" at the end, the onChildChanged method wasn't fired only on my first item because the previousChildName for it was actually null.
So, I changed p1: String
to p1: String?
and problem solved!
It didn't work like this:
override fun onChildChanged(p0: DataSnapshot, p1: String) { ... }
It works this way!:
override fun onChildChanged(p0: DataSnapshot, p1: String?) { ... }