2016-03-19 28 views
1

我想在未授权之前从Firebase中删除数据。问题是,mFirebaseRef.unauth()仅适用于查询不为空的情况。但即使查询为空,我也需要它。如何检查Firebase查询是否为空

final Firebase pushNotificationRef = new Firebase(Constant.FIREBASE_URL_PUSHNOTIFICATIONS); 
    final Query queryRef = pushNotificationRef.orderByChild("deviceToken").equalTo(token); 
    queryRef.addChildEventListener(new ChildEventListener() { 
     @Override 
     public void onChildAdded(DataSnapshot dataSnapshot, String s) { 
      if (dataSnapshot.exists()) { 
       Log.e("MyTag", dataSnapshot.getKey()); 
       pushNotificationRef.child(dataSnapshot.getKey()).removeValue(); 
      } 
      mFirebaseRef.unauth(); 
     } 
+0

的'onChildAdded()'方法将只能被称为** **如果孩子存在,所以你不能用它来检测何时不存在孩子。看到这个问题如何检测:http://stackoverflow.com/questions/34460779/what-happens-if-a-firebase-url-doesnot-exist-and-we-try-to-add-a-listener -to-IT/34463972#34463972 –

回答

3

使用本...

if (dataSnapshot.exists()) 
    // user found 
else 
    // user not found 

演示的例子

Query query = dbstud.child("users").orderByChild("name").equalTo("XYZ"); 

query.addValueEventListener(new ValueEventListener() { 
    @Override 
    public void onDataChange(DataSnapshot dataSnapshot) { 

     if(dataSnapshot.exists()) { 
     for (DataSnapshot snapshot : dataSnapshot.getChildren()) { 


       Toast.makeText(getApplicationContext(), "id = " + snapshot.getKey(), Toast.LENGTH_LONG).show(); 
      } 

     } 
     else { 
      Toast.makeText(getApplicationContext(), "User Not found ", Toast.LENGTH_LONG).show(); 


     } 
    } 

    @Override 
    public void onCancelled(DatabaseError databaseError) { 
     throw databaseError.toException(); 
    } 
}); 
相关问题