Firebase query with wrong data doesn't give any call back [duplicate]

孤者浪人 提交于 2019-12-24 01:58:14

问题


I have created a table in firebase and saved couple of data and want to query specific data by specifying inputs like where condition in Sqlite :

Query queryRef = ref.orderByChild("name").equalTo(username); 

queryRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String previousChild) { 
       // i get the call back if i specify username which is already there in table 
    } 
});

my problem is when i pass any value which doesn't exist in table then i don't get any call back.

how to handle such scenario in Firebase. is there any other call back which i should be listening to ?


回答1:


Replace your addChildEventListener listener with addListenerForSingleValueEvent for single value you get call back defiantly like following ,

 Query queryRef = ref.orderByChild("name").equalTo(username);
        queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                //if match your data otherwise return null
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });



回答2:


You should be using addValueEventListener(). You can find more details on this other similar question.

But your code will look like the following and you will be able to see if there is some matching results using snapshot.exists().

 Query queryRef = ref.orderByChild("name").equalTo(username); 

 queryRef.addValueEventListener(new ValueEventListener() {

     @Override
     public void onDataChanged(DataSnapshot snapshot) {
       if (snapshot.exists()) {
         //found results
       }
       else {
         //not found
       }
     }

  });


来源:https://stackoverflow.com/questions/37812136/firebase-query-with-wrong-data-doesnt-give-any-call-back

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!