Why this ChildEventListener is not reading data fr

2019-09-19 12:45发布

问题:

I have a query to firebase node with ChildEventListener shown in image link

now when I run this code

mMessageRef.child(ScrollAppUtils.firebaseId).child(child.key).orderByKey().limitToLast(1).addChildEventListener(object : ChildEventListener {

    override fun onCancelled(p0: DatabaseError?) {}

    override fun onChildMoved(p0: DataSnapshot?, p1: String?) {}

    override fun onChildChanged(p0: DataSnapshot?, p1: String?) {}

    override fun onChildAdded(p0: DataSnapshot?, p1: String?) {

        Logger.d("inside onChild Added")
        if (p0!!.hasChildren())
        {

        var lastMessage = p0.getValue(MessagesTwo::class.java)
        var dialog = DefaultDialog(child.key, user.metaData.profileImage, user.metaData.name, arrayListUser, lastMessage, 2)
        if (!listDialog.contains(dialog)) {

            listDialog.add(dialog)
            Logger.d(listDialog.size)
            dialogListAdapter.setItems(listDialog)
            dialogListAdapter.notifyDataSetChanged()
        } else {
            Logger.d("inside updateItemByID : ")
            Logger.json(Gson().toJson(dialog))
            dialogListAdapter.updateItemById(dialog)
            dialogListAdapter.notifyDataSetChanged()
        }
        }


    }

    override fun onChildRemoved(p0: DataSnapshot?) {}
    })

this listener simply doesn't work when a node not found, which I believe should work as ValueEventListener is working very well but I have some other problem with that listener so I am compelled to use this listener. Please suggest me what is I am doing wrong here?

回答1:

The onChildAdded method is called for each child not of the location (or query). If there are no matching child nodes, onChildAdded will not be called.

If you want to detect the situation where there are no child nodes, you'll (also) need to use a ValueEventListener.

Also see:

  • Firebase onChildAdded not called when there is no data (which this question is really a duplicate of)
  • Can I determine if query does NOT find any children with values within a specified range?
  • What happens if a firebase url doesnot exist and we try to add a listener to it?
  • Firebase queryOrderedbyChild doesn't return a Null value