I'm trying to make a read query timeout with Firebase Database when there is no internet connection or any other problem. The problem is that even when the timeout takes effect and the listener is removed, it still gets called even though it has been removed. How can I prevent that? What's the best way to handle timeout?
Here's my code :
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("key");
final ValueEventListener listener = new ValueEventListener() { /* ... */ };
ref.addListenerForSingleValueEvent(listener);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
ref.removeEventListener(listener);
}
}, 5000);
Someone here seems to have the same issue but I don't understand the solution.
There is nothing like timeout in the Firebase API, hence timeouts should be handled using our own logic. This is how i implement timeouts in my code.
private void getDataFromFirebase()
{
final boolean[] gotResult = new boolean[1];
gotResult[0] = false;
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference dataReference = firebaseDatabase.getReference().child("data");
ValueEventListener dataFetchEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
gotResult[0] = true;
// You async code goes here
}
@Override
public void onCancelled(DatabaseError databaseError) {
gotResult[0] = true;
}
};
if(isNetworkAvailable()) {
dataReference.addListenerForSingleValueEvent(dataFetchEventListener);
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
timer.cancel();
if (gotResult[0] == false) { // Timeout
dataReference.removeEventListener(dataFetchEventListener);
// Your timeout code goes here
}
}
};
// Setting timeout of 10 sec to the request
timer.schedule(timerTask, 10000L);
}
else{
// Internet not available
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With