繁体   English   中英

如何将数据快速加载到从 firestore 获取的应用程序中?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM