Firebase了解addValueEventListener添加或删除的数据

时间:2018-06-14 01:40:38

标签: android firebase firebase-realtime-database

我是firebase的新手,我写过这样的查询。问题是我不知道是添加还是删除了数据。我该如何区分?

    Query queryRoom = FirebaseDatabase.getInstance().getReference().child("Conversation").child(conversationID);

    queryRoom.keepSynced(true);

    queryRoom.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Conversation conversation = dataSnapshot.getValue(Conversation.class);
            if (conversation != null) {
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

1 个答案:

答案 0 :(得分:0)

您需要使用ChildEventListener代替ValueEventListener来区分操作。当任何一个孩子添加,删除,更改,移动和取消时,ChildEventListener都是用户触发器。

虽然建议使用ChildEventListener来读取数据列表,但有时候将ValueEventListener附加到列表引用是有用的。

ValueEventListener附加到数据列表会将整个数据列表作为单个DataSnapshot返回,然后您可以循环访问这些数据。

您应该从https://firebase.google.com/docs/database/admin/retrieve-data#section-event-types文档中获取更多信息。

赞:

ChildEventListener childEventListener = new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
        Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());

        // A new comment has been added, add it to the displayed list
        Comment comment = dataSnapshot.getValue(Comment.class);

        // ...
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
        Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());

        // A comment has changed, use the key to determine if we are displaying this
        // comment and if so displayed the changed comment.
        Comment newComment = dataSnapshot.getValue(Comment.class);
        String commentKey = dataSnapshot.getKey();

        // ...
    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {
        Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());

        // A comment has changed, use the key to determine if we are displaying this
        // comment and if so remove it.
        String commentKey = dataSnapshot.getKey();

        // ...
    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
        Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());

        // A comment has changed position, use the key to determine if we are
        // displaying this comment and if so move it.
        Comment movedComment = dataSnapshot.getValue(Comment.class);
        String commentKey = dataSnapshot.getKey();

        // ...
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.w(TAG, "postComments:onCancelled", databaseError.toException());
        Toast.makeText(mContext, "Failed to load comments.",
                Toast.LENGTH_SHORT).show();
    }
};
ref.addChildEventListener(childEventListener);