I'm working with firestore in android. I want to allow my user to save the data in app during the offline mode.(Data insertion during offline is also working fine) But I don't know how I can detect that data is added in offline mode, I need to get document id that is added. In the online mode I can detect the data insertion with the listener as.
Map<String, Object> data = new HashMap<>();
data.put("name", "Tokyo");
data.put("country", "Japan");
db.collection("cities")
.add(data)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
I also need to detect that is added when the app is offline. So how I can? Because these listeners only works when the data is inserted in the server and app get the response from the server.
Offline insert listener. Based on my code test, it is just fine to remove both the success and snapshot listeners. simply check if a document id is not null and its length is greater than 10. that was enough for me to conclude a successful insert. code :
Thank you Frank for your earlier clue. The add() will always write the document to the local .....in my case the set() method.
The
addOnSuccessListener
only gets called once the data is committed to the server. That's its explicit goal. If you local client also need the data after it's added locally, you'll do that with a regularaddSnapshotListener
.From the documentation on events for local changes:
See the linked documentation for sample code of how to process this.
Update: if you're just trying to get the ID of a new document, you can simply do:
See
CollectionReference.document()
.