Reputation: 33
We are building an Android app, and our database is on Firebase. I want to read a data from the database (let's say store it in a global String variable sampleString) and use it throughout the code. However, when I use a listener, I can only use sampleString inside the listener. When I try to reach it from other places in the code, it always returns null.
I want my function sampleFunction to be called only after the listener reads the value from database. In the cases where the sampleFunction also makes a database read, it only works when I copy-paste the whole function inside the listener, and doesn't work if I just call the function inside the listener, because the value of sampleString stays null. I tried to put a wait function before calling sampleFunction, but it still doesn't work. And copy-pasting the same function whenever I need to use it makes the code a mess. How can I solve this?
Code:
String sampleString;
Boolean isSame;
void sampleFunction() {
myAnotherRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
sampleString2 = dataSnapshot.child("name").getValue().toString();
same = sampleString.equals(sampleString2); //returns false because sampleString always seems null.
}
//...
}
}
void main(){
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
sampleString = dataSnapshot.child("name").getValue().toString();
sampleFunction();
if(isSame){ //returns false because in sampleFunction, sampleString always seems null.
//...
}
}
//...
}
//...
}
So how can I make sampleFunction wait until sampleString is loaded with data from database? The code works if I copy-paste the sampleFunction to main, but then I have to do this more than a few times and code looks terrible.
Upvotes: 1
Views: 2831
Reputation: 317372
Database operations are asynchronous, which means you typically don't make any other function wait for it to complete. Especially if that other function is running on the main thread. Never block the main thread.
Also, you probably want to use addListenerForSingleValueEvent() instead of addValueEventListener(), as the former will trigger only once when data is found, whereas the latter will continually listen for changes and trigger for each new change after the listener was added.
You can restructure your code by calling another function inside the callback instead of deeply nesting your callbacks. That should make it easier to read.
Upvotes: 2