The below code inserts data in the Firebase database and runs fine when my Android device has network connectivity. However, if I'm offline it does not sync directly with the online database. I would like to be notified if it's being cached rather than being synced directly.
DatabaseReference databaseIssue;
databaseIssue = FirebaseDatabase.getInstance().getReference("Issue");
String timeDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
databaseIssue.child(timeDate).setValue("test");
Is there anyway to implement somthing like simple try/catch around:
databaseIssue.child(timeDate).setValue("test");
A catch if the data is only cached?
From the Firebase documentation (https://firebase.google.com/docs/database/admin/save-data)
Adding a Completion Callback
DatabaseReference dataRef = ref.child("data");
dataRef.setValueAsync("I'm writing data", new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
System.out.println("Data could not be saved " + databaseError.getMessage());
} else {
System.out.println("Data saved successfully.");
}
}
});
The set value does throw other exceptions: Firebase: Permission denied - setValue()
Does firebase throw an exception if it cannot connect to the online database and has to cache the data? Is there a way to log, if the data is being cached or synced?
Network Connectivity and Offline Writes
Firebase Node.js and Java clients maintain their own internal version of >any active data. When data is written, it is written to this local version first. The client then synchronizes that data with the database and with other clients on a 'best-effort' basis.
As a result, all writes to the database will trigger local events immediately, before any data has even been written to the database. This means that when you write an application using Firebase, your app will remain responsive regardless of network latency or Internet connectivity.
Once connectivity is reestablished, we'll receive the appropriate set of events so that the client "catches up" with the current server state, without having to write any custom code.