Firestore Offline Write/Add Not Working

Viewed 875

We are able to get Firestore to download records to the local cache and can read those records. However, we are unable to update a record and not able to add a new record.

Have even tried some of the same code (https://github.com/firebase/quickstart-android) but don't seem to be able to get the offline write/insert working - only read.

When we call this function offline it gets called OnFailureListner and throws an exception

 @Override
public void onRating(Rating rating) {
    // In a transaction, add the new rating and update the aggregate totals
    addRating(mRestaurantRef, rating)
            .addOnSuccessListener(this, new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.d(TAG, "Rating added");

                    // Hide keyboard and scroll to top
                    hideKeyboard();
                    mRatingsRecycler.smoothScrollToPosition(0);
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(TAG, "Add rating failed", e);

                    // Show failure message and hide keyboard
                    hideKeyboard();
                    Snackbar.make(findViewById(android.R.id.content), "Failed to add rating",
                            Snackbar.LENGTH_SHORT).show();
                }
            });
}
1 Answers

You can't simply write data offline because Firestore can get the data and upload it whenb you have an Internet connection (which requires a task going in the background). Firestore has improved its offline capabilities but you can always choose to create your own service to upload it when the device connects.

Android lets you create Services. From developer.android.com:

A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity. Another component, such as an activity, can start the service and let it run or bind to it in order to interact with it. A service is implemented as a subclass of Service.

So you could create a Service which keeps waiting for an Internet connection and just calls the FirebaseFirestore object to upload all the data you want.

This may help you, this is the official Android information about services: https://developer.android.com/guide/components/services.html

Related