【问题标题】:Android share firestore data with entire appAndroid 与整个应用共享 Firestore 数据
【发布时间】:2018-05-12 10:48:56
【问题描述】:
我的 MainActivity 有一个由 4 个 Fragment 填充的 TabView,每个 Fragment 使用 Firestore DocumentReference 获取数据,这导致我的应用程序为每个 TAB 再次下载数据。我想在我的 MainActivity 中获取 DocumentReference 中的数据,并在我的 4 个片段甚至不同的 Activity 之间共享该 DocumentReference。
这可能吗?
我的 Firestore DocumentReference 包含对象,所以我不确定它是否适用于共享首选项。
【问题讨论】:
标签:
android
firebase
android-fragments
google-cloud-firestore
【解决方案1】:
使用 Android Firestore SDK,offline persistence 默认启用。这意味着当一个文档被获取时,它将保留在设备上的本地缓存中,并且不会被再次下载以供后续访问(除非该文档在服务器上发生了更改,或者因为缓存也增长了而被从缓存中逐出大)。
对于您的情况,我怀疑您实际上是在多次获取文档,除非您禁用持久性。
【解决方案2】:
您可以为 Firestore 操作创建一个单独的类。
public class FirebaseUtils {
public static DocumentReference getFirestoreUserDocRef(String documentName) {
return FirebaseFirestore.getInstance().collection("users").document(documentName);
}
}
您可以访问项目中的任何位置。
希望对你有帮助。