androidgoogle-cloud-firestoreoffline-caching

Upload Firestore Cache Write Data Upon Getting Internet


My app allows the user make firestore writes when the user is offline. I have noticed that cache data is only written to firestone when the user makes another write (so it takes all the initial writes when user was offline, and then adds the new write data and send to firestore).

I am looking for a way to send the cached data to firestore without the user having to make another write entry. Please how can I achieve this functionality? I'd greatly appreciate any help you can provide


Solution

  • You can get around this by detecting when the user gets an internet connection again, I suggest prompting the user before doing so. But when this event is done. I suggest writing to a dedicated location with a "last updated' field such as a dedicated collection for all users where you can track the last update timestamp, it'll incur a write but this way you have control over it.

    It will require permission to check from the device such as a simple query to a URL, or ideally with the getActiveNetworkInfo() method from the ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none of the interfaces are connected.

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    

    You will also need:

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> in your android manifest.

    Note that having an active network interface doesn't guarantee that a particular networked service is available.