Feroz Siddiqui Feroz Siddiqui - 2 months ago 40
Android Question

How to Handle Offline Transactions in Firebase Realtime Database?

I have an

addValueEventListener
which listens to any value changes in Firebase Realtime Database. In online mode, everything is working fine.

But in offline mode, device is offline and my Web Server has done multiple transactions on Firebase Realtime Database on same value for which I put the listener from Android. After the device comes online, it will only listen for the last transaction and skipping the other transactions done in between.

PFB reference link. PFB code which i have done so far:

FirebaseDatabase.getInstance().setPersistenceEnabled(false);
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = firebaseDatabase.getReference("mykey");
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, Object> key_Value = (HashMap<String, Object>) dataSnapshot.getValue();
for (String key : key_Value.keySet()) {
System.out.println("firebase key is "+key);
}

@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("feroz ", "Failed to read value.", error.toException());
}
});
}

Answer

The Firebase Realtime Database stores information came back from an inquiry for use when disconnected. For questions developed while disconnected, the Firebase Realtime Database keeps on working for already stacked information. On the off chance that the asked for information hasn't stacked, the Firebase Realtime Database loads information from the nearby reserve. When we return online our information will stack and mirror the inquiry.

For instance, here we have a bit of code in our application that questions for the last four things in our Firebase Realtime Database of scores

DatabaseReference scoresRef = FirebaseDatabase.getInstance().getReference("scores");
scoresRef.orderByValue().limitToLast(4).addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot snapshot, String previousChild) {
      System.out.println("The " + snapshot.getKey() + " dinosaur's score is " + snapshot.getValue());
    }
});