首页 > 解决方案 > 如何将数据快速加载到从 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时,它会快速加载,但是当我删除缓存或从其他帐户登录时,会出现相同的缓存。

那么,我怎样才能快速加载数据。

标签: javaandroidfirebasegoogle-cloud-firestorelocal-storage

解决方案


您可以使用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());
        }
    }
});

推荐阅读