gpt4 book ai didi

java - 离线时强制从 Cloud Firestore 缓存获取

转载 作者:行者123 更新时间:2023-12-01 19:46:32 24 4
gpt4 key购买 nike

我目前正在将 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 从缓存中获取数据,而不是尝试从服务器中获取数据?提前致谢

最佳答案

Is there some way to tell firestore explicitly to bring data from the cache instead of trying to fetch it from the server?

是的,从 16.0.0 开始SDK版本更新,可以借助 DocumentReference.get(Source source) 来实现和 Query.get(Source source)方法。

By default, get() attempts to provide up-to-date data when possible by waiting for data from the server, but it may return cached data or fail if you are offline and the server cannot be reached. This behavior can be altered via the Source parameter.

因此您可以将其作为参数传递给 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 。更多信息here .

关于java - 离线时强制从 Cloud Firestore 缓存获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53052706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com