Al Walid Ashik
Al Walid Ashik

Reputation: 1779

Stop getting Real Time update on Firebase Database Reference

I know firebase database is a real time database but for my feature I don't want to update a specific database reference (below reference) value in real time. So, is there any way to stop getting real time update on firebase database reference?

mUserDataRef = FirebaseDatabase.getInstance().getReference().child("users");

Upvotes: 0

Views: 1616

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599956

The code you shared only creates a reference to a location in the database. It does not start getting realtime updates yet. To start getting realtime update, attach a listener with addValueEventListener or addChildEventListener. An example of the latter:

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

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

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

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

  @Override
  public void onCancelled(DatabaseError databaseError) {
    Log.w(TAG, "onCancelled", databaseError.toException());
  }
};
mUserDataRef.addChildEventListener(childEventListener);

This will receive data updates until the listener it removed. To remove the listener, call:

mUserDataRef.removeEventListener(childEventListener);

If you only want to get data once, instead of receiving continuous updates, you can call addListenerForSingleValueEvent:

mUserDataRef.addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
        Log.d(TAG, "onDataChange:" + dataSnapshot.getKey());
    }
  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    Log.w(TAG, "onCancelled", databaseError.toException());
  }
});

I highly recommend studying these two pages in the Firebase documentation:

Upvotes: 2

Related Questions