I'm facing an issue regarding the Firebase Realtime database and in particular the value event listener which fires more than once .Seems that when the Internet state changes from on to off several times and the device finally has stable connection the onDataChange(DataSnapshot dataSnapshot) callback method of the listener is invoked with dataSnapshot of null content.Seems that the Realtime Database refers to the app's local cache and in that case I do not have any data stored in it. I am attaching the listener inside the Activity onStart() or when the device has established some connection ; I am detaching the listener inside the Activity onStop() method or when the device looses internet connection .Only one instance of a given listener exists at a time and every attach has corresponding detach action executed when needed. I have tried to wait a while between the change of the connection states before attaching the listener and to reattach the listener if the datasnapshot returns null .None of those worked.Please advice for a solution.
Some example code inside an Activity :
private ValueEventListener listener;
private Query query;
private boolean hasAttachedListener;
private Query getDatabaseReference() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
return reference.child(“some child ref”)
.child(“other child ref 2 ”);
}
private ValueEventListener getDatabaseListener() {
return new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(“firebase”, dataSnapshot.toString());
//issue here datasnapshot is null sometimes
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(“firebase”, databaseError.getDetails());
}
};
}
/**
* Attaches listener
*/
public void addListener() {
if (!hasAttachedListener) {
query = getDatabaseReference();
listener = getDatabaseListener();
query.addValueEventListener(listener);
hasAttachedListener = true;
}
}
/**
* Detaches the attached listener
*/
public void removeListener() {
if (hasAttachedListener) {
query.removeEventListener(listener);
query = null;
listener = null;
hasAttachedListener = false;
}
}
@Override
protected void onStart() {
super.onStart();
addListener();
}
@Override
protected void onStop() {
super.onStop();
removeListener();
}
@Override
protected void onNetworkDisconnected() {
super.onNetworkDisconnected();
// invoked when internet connection is lost
removeListener();
}
@Override
protected void onNetworkReconnected() {
super.onNetworkReconnected();
// invoked when internet connection is restored
addListener();
}