问题
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