I want to remove addValueEventListener listener from a firebase ref when value of particular field is true.
ValueEventListener valueListener=null;
private void removeListener(Firebase fb){
if(valueListener!=null){
**fb.removeEventListener(valueListener);**
}
}
String key="https://boiling-heat-3083.firebaseio.com/baseNodeAttempt/" + userId+"/"+nodeType+"/"+nodeId+"/data";
final Firebase fb = new Firebase(key);
valueListener=fb.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snap) {
final HashMap<String, Object> data=(HashMap<String, Object>) snap.getValue();
if( data.get("attemptFinish_"+nodeId)!=null){
boolean title = (boolean) snap.child("attemptFinish_"+nodeId).getValue();
if(title){
removeListener(fb);
}
}
}
@Override
public void onCancelled() {
// TODO Auto-generated method stub
}
});
But addValueEventListener is not getting removed and it's called for that firebase ref . So please suggest me how to remove listener from any firebase ref if required.
Detach listeners Callbacks are removed by calling the removeEventListener() method on your Firebase database reference. If a listener has been added multiple times to a data location, it is called multiple times for each event, and you must detach it the same number of times to remove it completely.
Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.
Detach listeners Callbacks are removed by calling the off() method on your Firebase database reference. You can remove a single listener by passing it as a parameter to off() .
You can use Firebase's REST API to get access to the "raw" data. You can use any Firebase URL as a REST endpoint. All you need to do is append ". json" to the end of the URL and send a request from your favorite HTTPS client.
You can remove the listener from within the callback with:
ref.removeEventListener(this);
So a complete fragment:
String key="https://boiling-heat-3083.firebaseio.com/baseNodeAttempt/" + userId+"/"+nodeType+"/"+nodeId+"/data";
final Firebase ref = new Firebase(key);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snap) {
if (snap.hasChild("attemptFinish_"+nodeId) {
boolean isFinished = (boolean) snap.child("attemptFinish_"+nodeId).getValue();
if(isFinished){
ref.removeEventListener(this);
}
}
}
@Override
public void onCancelled() {
// TODO Auto-generated method stub
}
});
I removed the HashMap
, instead using the methods of the DataSnapshot
to accomplish the same. I also renamed a few variables to be clearer/more idiomatic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With