问题描述
我想在特定字段的值为true时从firebase ref中删除addValueEventListener侦听器。
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
}
});
但是没有删除addValueEventListener并且为firebase ref调用它。因此,如果需要,请建议我如何从任何firebase引用中删除侦听器。
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.
推荐答案
您可以从回调中删除侦听器:
You can remove the listener from within the callback with:
ref.removeEventListener(this);
所以一个完整的片段:
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
}
});
我删除了 HashMap
,而不是使用方法 DataSnapshot
来实现同样的目标。我还将一些变量重命名为更清晰/更具惯用性。
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.
这篇关于removeEventListener不删除firebase中的侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!