[英]How to load data quickly into app that is fetched from firestore?
我是菜鳥Android開發者,日常學習。 現在我遇到了一個困擾我一周的問題。
在我的應用程序中,我使用 firebase firestore 加載數據(主要是圖像和文本視圖)。 這工作正常,但現在我在我的應用程序中發現了一個問題,當用戶打開應用程序時,從 firestore 獲取的數據一次又一次地發生,即使數據是相同的。 這增加了我在 firebase 中的讀取操作,也需要時間將數據加載到它們的字段中。 因此,為了快速響應用戶,我想從本地加載數據。
所以,我想知道我該怎么做。 如何從 firestore 保存數據並從本地存儲加載數據,這使得它變得快速和容易。
說明:我嘗試了緩存加載並且效果很好,但是當用戶清除應用程序數據並再次打開應用程序時,數據不會像之前那樣從服務器獲取。 那么,如果緩存從緩存中加載,是否有一種方法可以檢查緩存是否從服務器加載為空。
示例代碼:
Source source = Source.CACHE;
if (user != null){
user_id = user.getUid();
DocumentReference reference = FirebaseFirestore.getInstance().collection("Users").document(user_id);
reference.get(source).addOnCompleteListener(task -> {
if (task.isSuccessful()){
DocumentSnapshot snapshot = task.getResult();
if (snapshot != null) {
if (snapshot.exists()){
name = String.valueOf(snapshot.get("Name:"));
editName.setText(name);
email = String.valueOf(snapshot.get("Email:"));
editEmail.setText(email);
mobile = String.valueOf(snapshot.get("Phone:"));
editMobile.setText(mobile);
dob = String.valueOf(snapshot.get("Date of Birth:"));
editDOB.setText(dob);
}else {
editName.setText(user.getDisplayName());
editEmail.setText(user.getEmail());
editMobile.setText(user.getPhoneNumber());
}
}
}
});
在上面的代碼中,當我首先從父活動移動到此活動時,編輯文本字段為空,3 秒后它們獲得了它們的值。 但是當我使用Source.CACHE時它會快速加載但是當我刪除緩存或從其他帳戶登錄時會出現相同的緩存。
那么,我怎樣才能快速加載數據。
您可以使用Source Options從本地緩存中讀取。 從那個鏈接:
對於具有離線支持的平台,您可以設置
source
選項來控制get
調用如何使用離線緩存。默認情況下,get 調用將嘗試從您的數據庫中獲取最新的文檔快照。 在支持離線的平台上,如果網絡不可用或請求超時,客戶端庫將使用離線緩存。
您可以在
get()
調用中指定源選項以更改默認行為。 您可以僅從數據庫中獲取而忽略離線緩存,也可以僅從離線緩存中獲取。 例如:// Source can be CACHE, SERVER, or DEFAULT. Source source = Source.CACHE; // Get the document, forcing the SDK to use the offline cache docRef.get(source).addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { // Document found in the offline cache DocumentSnapshot document = task.getResult(); Log.d(TAG, "Cached document data: " + document.getData()); } else { Log.d(TAG, "Cached get failed: ", task.getException()); } } });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.