0

Firestore call onComplete etc events only online. How do know about write status offline.

 db.collection("col").document(id).set(obj)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                          //Ok finish activity <----
                            finish();
                        } else {
                            Toast toast = Toast.makeText(getApplicationContext(),
                                    "Error try again", Toast.LENGTH_SHORT);
                            toast.show();
                        }
                    }
                });

The code above doesn't works offline, and i can write multiple times. onComplete will not called until i connect to internet. Ho do i implement this feature(closing activity when success).

Valera Kvip
  • 334
  • 5
  • 14

2 Answers2

2

onComplete will not be called until I connect to the internet.

That's normal behavior. The OnCompleteListener is called only when the data has been written or rejected by the Firebase servers.

A listener will never fire for local write operations. If the local write operation were to fail, the client will raise a regular exception. The Firestore client is designed to continue working even if offline. So writing some data to the database while offline will never produce an error.

Ho do I implement this feature(closing activity when success).

There is no way you can add a completion listener to know when the data is written to the cache and this is because this operation is happening instantly. There is nothing you should worry about in this situation.

What you can in such cases is to check the internet connection. If you are offline, it means that all data is added to the local cache.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
1

Offline writes are considered to be written immediately. There is no completion status for that.

You'll notice that if you have a listener set up for the document that's being written, that listener will trigger immediately, while offline, with the updated document values. You can tell from the document snapshot delivered to the listener if the write has completed or not. If you call snapshot.getMetadata().hasPendingWrites(), it will tell you whether or not the updated document has actually been sent. This is the best possible information you can receive about the status of offline writes.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441