Detect value change with firebase ValueEventListener

前端 未结 1 1917
遥遥无期
遥遥无期 2021-01-28 23:41

I am trying to detect value change from my Firebase Database. Here is my code for initializing the ValueEventListener:

valueEventListener = new ValueEventListene         


        
1条回答
  •  粉色の甜心
    2021-01-29 00:24

    There is nothing built to the Firebase Realtime Database to tell you what specific data under the snapshot has changed in the onDataChange method.

    If you want to know what specific property has change, you'll need to:

    1. Keep the snapshot that you get in onDataChange in a field.
    2. When onDataChange gets called, compare the data in the new snapshot with the data in the field.

    Say that you have a reference on a node in your JSON, and under that node is a status property, and you want to both listen to the entire node, and detect if the status has changed.

    You'd do that with something like:

    // Add a field to your class to keep the latest snapshot
    DataSnapshot previousSnapshot;
    
    // Then add your listener
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            bool wasActive = false;
            if (previousSnapshot != null && previousSnapshot.child("status").exists()) {
                wasActive = dataSnapshot.child("status").getValue(Boolean.class);
            }
            boolean isActive = dataSnapshot.child("status").getValue(Boolean.class);
    
            if (isActive <> wasActive) {
                ... the user's status changed
            }
    
            previousSnapshot = dataSnapshot;
        }
    
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            throw databaseError.toException(); // never ignore errors
        }
    });
    
    

    0 讨论(0)
提交回复
热议问题