Java – Is there some flag about Firestore that I can check if the data is online/offline?

Is there some flag about Firestore that I can check if the data is online/offline?… here is a solution to the problem.

Is there some flag about Firestore that I can check if the data is online/offline?

I < a href="https://firebase.google.com/docs/firestore/query-data/get-data" rel="noreferrer noopener nofollow">read when in offline mode on Android, unless the device is online The onComplete() method will never return, so data can be persisted to Firestore’s backend.

When I was in offline mode and did this get() I noticed that it returned what I thought had to be local data because I had setPersistenceEnabled(true).

  query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
      @Override
      public void onComplete(@NonNull Task<QuerySnapshot> task) {

}
  });

I just wanted to ask if this is correct? If so, are there some flags I can check if the data is online/offline?

Sometimes doing this get() doesn’t return, just stuck there forever, which could be related to my device getting hot after a lot of debugging.

Solution

Unlike enabling offline persistence in the Firebase real-time database, you should start with the following line of code:

FirebaseDatabase.getInstance().setPersistenceEnabled(true);

In Cloud Firestore, offline persistence is enabled by default for Android and iOS. Therefore, there is no need to use: setPersistenceEnabled(true).

When you go offline and use the get() call, the results come from a cached copy of the Cloud Firestore data that your app is using.

To check if the data is coming from the cache or from the Firestore server, you can use the following line of code:

String source = querySnapshot.getMetadata().isFromCache() ? "Local Cache" : "Firebase Server";

Related Problems and Solutions