Android - Firebase Offline Best Practices

Taken from here

Not sure, if it is relevant here. But there is another scenario when this crash can happen.

If your app has a service (with different process) and you're creating your own Application class, the service and the foreground app will use the same Application class (not same instance) to initialize. Now when I am using com.google.firebase:firebase-crash dependancy to handle crashes, it creates a background service your.app.packagename:background_crash. For some reason, this was inducing crashes on my app. Specifically, because in my Application class, I was making a call like,

FirebaseDatabase.getInstance().setPersistenceEnabled(true);

I am assuming, the background service when initing with our Application class, somehow Firebase is not initialized. To fix this, I did

if (!FirebaseApp.getApps(this).isEmpty())
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);

setPersistenceEnabled() should be called once on startup, before you retrieve your first reference of the database. I call mine directly after I call FIRApp.configure()

Persistence enabled allows for complete offline retention of information. The significant component of this is that offline requests and updates will be completed, even if you force-close the app and reopen it. If you're looking for offline access that's the boolean to set.

Keep sync is used for if circumstances where you want up to date data cached for whenever you retrieve the information, but don't necessarily need that data to be restored when you next open the app.

A good example of use would be if you had views which accessed the logged in user details. Instead of having user detail listeners on all views which use the details, you can just specify to keep that database reference synced and you can get up to date data quicker.

More details on persistence and syncing can be read here in the Firebase documentation: https://firebase.google.com/docs/database/android/offline-capabilities


Create an Application Class

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);

    }
}

And Change your manifest as

<application
    android:name=".MyApp"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"