Issue
I'm writing an android app using java. i have it connected to Realtime database. I'm trying to search my data and check if a certain key exists in it or not.
public boolean checkForKey(String key) {
final boolean[] found = {false};
ValueEventListener listener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
if(dataSnapshot.getKey().equals(key)) {
found[0] = true;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
};
dbRef.child("Polls").addValueEventListener(listener);
return found[0];
}
The function is returning false before it finishes the part of the code that actually searches through the database. Any help in explaining why does this happen is appreciated.
Solution
From the docs:
onDataChange: This method will be called with a snapshot of the data at this location. It will also be called each time that data changes.
When the data changes, whatever is inside the method will be executed. In other words, the method onDataChange
instructs the program what to do when it gets results (which could be whenever)
This is asynchronous behaviour - as @Turing85 points out, this will only be called when the data changes.
If you want to know if something with this key exists, you could construct a query and then call get()
method which would return a Task<DataSnapshot>
. For this task, you could attach addOnCompleteListener
listener to do what you would like. This would also be asynchronous, so it would only run when there is a result.
Answered By - ferrouskid
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.