我具有以下代码,用于从Firebase中删除某些数据:
public void removeGameFromWaitQueue() {
final DatabaseReference data = FirebaseDatabase.getInstance().getReference().child("games").child(mCurrentGameKey);
data.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
mCurrentGame = snapshot.getValue(DatabaseModels.Game.class);
if (mCurrentGame.getState() == DatabaseModels.Game.State.OPEN.ordinal()){
data.removeValue();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
我如何检查“数据”是否存在,然后执行所有其他代码?这意味着,如果我创建DatabaseReference,则代码有效。但是,当然,如果我不创建引用,那么我将没有任何例外。我应该为此安排2位听众吗?如果是的话,最好的方法是什么?
答案 0 :(得分:0)
为以后的参考,我像这样解决了它:
public void removeGameFromWaitQueue() {
final DatabaseReference data = FirebaseDatabase.getInstance().getReference().child("games").child(mCurrentGameKey);
data.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
mCurrentGame = snapshot.getValue(DatabaseModels.Game.class);
if (mCurrentGame.getState() == DatabaseModels.Game.State.OPEN.ordinal()){
data.removeValue();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void removeAfterCheck(){
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.hasChild("games")) {
removeGameFromWaitQueue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
也许有更好的方法,但这在我想要的所有情况下都对我有效。