java - 离线时强制从 Cloud Firestore 缓存中提取
问题描述
我目前正在将 Firebase Firestore 用于 Android 项目,但是当手机处于飞行模式时,我在检索数据时遇到了一些问题。这是我的代码:
public void loadThings() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("medidas").whereEqualTo("id_user", mAuth.getCurrentUser().getUid()).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
QuerySnapshot snapshot = task.getResult();
int tam = snapshot.getDocuments().size();
data = new String[tam];
StringBuilder temp;
DocumentSnapshot doc;
for (int i = 0; i < tam; i++) {
temp = new StringBuilder();
doc = snapshot.getDocuments().get(i);
temp.append("Date: ").append(doc.get("fecha")).append(";");
temp.append("Min: ").append(doc.get("min")).append(";");
temp.append("Max: ").append(doc.get("max")).append(";");
temp.append("Avg: ").append(doc.get("avg")).append(";");
data[i] = temp.toString();
}
if(tam==0)
{
noMeasures();
}
}
else
{
data=null;
}
mLoadingIndicator.setVisibility(View.INVISIBLE);
mMeasuresAdapter.setMeasuresData(data);
if (null == data) {
showErrorMessage();
} else {
showMeasuresDataView();
}
}
});
}
具体问题是有时显示数据需要很长时间(超过 10 秒),而另一些则需要立即显示数据。由于手机处于飞行模式,很明显我正在检索的数据来自缓存。但是,我不明白为什么有时需要这么长时间。有没有办法明确告诉firestore从缓存中获取数据而不是尝试从服务器获取数据?提前致谢
解决方案
有没有办法明确告诉firestore从缓存中获取数据而不是尝试从服务器获取数据?
是的,从16.0.0
SDK 版本更新开始,您可以借助DocumentReference.get(Source source)和Query.get(Source source)方法来实现这一点。
默认情况下,
get()
通过等待来自服务器的数据,尽可能尝试提供最新数据,但如果您处于脱机状态且无法访问服务器,它可能会返回缓存数据或失败。可以通过 Source 参数更改此行为。
因此,您可以将作为参数传递给DocumentReference
或源,Query
以便我们可以强制从或 尝试服务器检索数据并回退到缓存。server only
chache only
所以在代码中可能看起来像这样:
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference docIdRef = db.collection("yourCollection").document("yourDocument");
docIdRef.get(Source.CACHE).addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
//Get data from the documentSnapshot object
}
});
在这种情况下,我们强制从CACHE
唯一检索数据。如果您想强制从SERVER
唯一检索数据,您应该作为参数传递给get()
方法,Source.SERVER
. 更多信息在这里。
推荐阅读
- c# - 如何使用坐标检查您的作品是否在 c# 中的 A 和 B 之间
- php - include_once 数组中的多个文件
- php - 我如何使用带有 id 的 guzzle laravel pacakge 发送获取请求
- c++ - 我如何从 C++ 中的字符串向量中读取
- listview - 动画 ListView.builder,以便将所选项目添加到堆栈中,并将 ListView 的其余部分平移到左侧
- cloud - 通过java代码创建表的DDL语句失败
- kerberos - Microsoft Kerberos 与 MIT kerberos
- javascript - 在nodejs中的ejs tample中不显示错误列表
- excel - 为什么我在这个 VBA 代码中只得到案例 1 的结果?
- laravel - Laravel 每次刷新时的新会话和提交登录表单时的 419