I have an app with many different fragments that use different types of Firebase Realtime Database actions (Queries, LiveData, writeOperations) on different nodes. Now I would like to enable offline capabilities on the real-time database such that queries, livedata and write operations are executed even if the device losses internet connection. In the official documentation, it is written that I just have to use the following code (https://firebase.google.com/docs/database/android/offline-capabilities?hl=en):
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
Now my question is where and how often do I have to use this line? Do I have to use it before each of the firebase operations (queries, LiveData, writeOperations) in every Java class, or do I only need it once in the MainActivity class or do I need it once per Fragment (maybe in the onCreate method)? And do I just need this one line of code or do I also need the other stuff mentioned on the site (like Keeping Data Fresh, Querying Data Offline, etc.)?
CodePudding user response:
Yes, that's right. You only have to use:
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
Now my question is where and how often do I have to use this line?
You can add that line of code, directly to your code, when the application starts. So you might consider creating a class that extends Application:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
}
But be careful to only call setPersistenceEnabled before you have called getReference() for the first time.
Regarding how often, you only need to call it once.
Do I have to use it before each of the firebase operations (queries, LiveData, writeOperations) in every Java class
No. By default, it caches all the databases. So if you perform different operations in different places in your application, all those operations are cached. Besides that, there is no way you can only cache partial data. It's all the database or nothing.
And do I just need this one line of code or do I also need the other stuff mentioned on the site (like Keeping Data Fresh, Querying Data Offline, etc.)?
You only need that line of code.