On iOS, if you change or remove data from Firebase and start the app, onChildChanged or onChildRemoved are getting called to deliver the changed/removed data. On Android, the methods are only called when the app is running but not after starting. (Why I need this: It's crucial for syncing eg for users using multiple devices). This is my code:
transactionsRef.child(depotname).addChildEventListener(object : ChildEventListener {
override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) {
// Handle event here } // Other override methods, such as onChildChanged, onChildRemoved, etc. })
println("onChildAdded : ${snapshot.key}}")
}
override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) {
//TODO("Not yet implemented")
println("onChildChanged : ${snapshot.key}}")
}
override fun onChildRemoved(snapshot: DataSnapshot) {
//TODO("Not yet implemented")
println("onChildRemoved : ${snapshot.key}}")
}
override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) {
//TODO("Not yet implemented")
}
override fun onCancelled(error: DatabaseError) {
//TODO("Not yet implemented")
}
})
Just FYI, onChildAdded is called immediately at the app starts.
CodePudding user response:
Ok we found the solution. You have to call setPersistenceEnabled(true)
for example in MyApplication.kt
class. Call like this:
Firebase.database(your_database_url_firebasedatabase.app).setPersistenceEnabled(true)
Now onChildChanged and onChildRemoved will be called immediately at app launch, provided you set the listener eg in MainActivity.
CodePudding user response:
The onChildAdded
method fires for each child node that exists under the node to which you attach the listener. After that, it fires when an additional child is added. The other method like onChildChanged
and onChildRemoved
will also fire right after that when an existing child is changed or removed.
What you're saying, can only take place if the listener is not removed according to the life cycle of your activity. This means that if the listener remains active, your app will continue to stay in sync with the Firebase servers. If you remove the listener correctly, then when you start the app, only the onChildAdded
is called, and right after that, the methods that correspond to the action that is performed.
Just FYI, onChildAdded is called immediately at the app start.
As mentioned above, that's the expected behavior.