当前位置: 首页 > 知识库问答 >
问题:

使用MVVM体系结构从FireStore检索数据

云开诚
2023-03-14

我正在尝试遵循Android架构原则,并希望您在我的FireStore数据库上实现它们。

目前,我有一个存储库class,它处理所有带有底层数据的查询。我有一个fragment,它需要一个set 文档中字段中的键,我想知道检索此数据的最佳方法是什么。在我的前一个问题中,Alex Mamo建议使用接口OnCompleteListener结合使用,因为从Firestore检索数据是异步

这种方法似乎是可行的,但我不确定如何将这个接口中的数据提取到我的片段的本地变量。如果我希望使用这个数据,我的代码必须在abstract方法的定义之内吗?

如果要将数据从Firestore获取到我的Fragment我必须将一个在片段中定义的interface对象作为参数传递到我的存储库,那么我是否仍然遵循MVVM原则?

这是使用存储库查询Firestore数据库的推荐方法吗?

下面是我的接口和调用ViewModel检索数据的方法:

public interface FirestoreCallBack{
    void onCallBack(Set<String> keySet);
}

public void testMethod(){
    Log.i(TAG,"Inside testMethod.");
    mData.getGroups(new FirestoreCallBack() {
    //Do I have to define what I want to use the data for here (e.g. display the contents of the set in a textview)?
        @Override
        public void onCallBack(Set<String> keySet) {
            Log.i(TAG,"Inside testMethod of our Fragment and retrieved: " + keySet);
            myKeySet = keySet;
            Toast.makeText(getContext(),"Retrieved from interface: "+ myKeySet,Toast.LENGTH_SHORT).show();
        }
    });
}

要对存储库调用viewmodel方法:

private FirebaseRepository mRepository;
public void getGroups(TestGroupGetFragment.FirestoreCallBack firestoreCallBack){
    Log.i(TAG,"Inside getGroups method of FirebaseUserViewModel");
    mRepository.getGroups(firestoreCallBack);
}

最后是查询我的FireStore数据库的存储库方法:

public void getGroups(final TestGroupGetFragment.FirestoreCallBack firestoreCallBack){
    Log.i(TAG,"Attempting to retrieve a user's groups.");
    userCollection.document(currentUser.getUid()).get().addOnCompleteListener(
            new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    if (task.isSuccessful()){
                        DocumentSnapshot document = task.getResult();
                        Log.i(TAG,"Success inside the onComplete method of our document .get() and retrieved: "+ document.getData().keySet());
                        firestoreCallBack.onCallBack(document.getData().keySet());
                    } else {
                        Log.d(TAG,"The .get() failed for document: " + currentUser.getUid(), task.getException());
                    }
                }
            });
    Log.i(TAG, "Added onCompleteListener to our document.");
}

已编辑

public void testMethod(){
    Log.i(TAG,"Inside testMethod.");
    mData.getGroups(new FirestoreCallBack() {
        @Override
        public void onCallBack(Set<String> keySet) {
            Log.i(TAG,"Inside testMethod of our Fragment and retrieved: " + keySet);
            myKeySet = keySet;
            someOtherMethod(myKeySet); //I know I can simply pass keySet.
            Toast.makeText(getContext(),"GOT THESE FOR YOU: "+ myKeySet,Toast.LENGTH_SHORT).show();
        }
    });

    Log.i(TAG,"In testMethod, retrieving the keySet returned: "+ myKeySet);
}

共有1个答案

赏夕
2023-03-14

例如,我只使用livedata将数据带到recyclerview中,而不是interface

首先,我们必须创建firestore查询。在本例中,我列出了集合中的所有文档。

public class FirestoreLiveData<T> extends LiveData<T> {

    public static final String TAG = "debinf firestore";

    private ListenerRegistration registration;

    private CollectionReference colRef;
    private Class clazz;

    public FirestoreLiveData(CollectionReference colRef, Class clazz) {
        this.colRef = colRef;
        this.clazz = clazz;
    }


    EventListener<QuerySnapshot> eventListener = new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
            if (e != null) {
                Log.i(TAG, "Listen failed.", e);
                return;
            }


            if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()) {
                List<T> itemList = new ArrayList<>();
                for (DocumentSnapshot snapshot : queryDocumentSnapshots.getDocuments()) {
                    T item = (T) snapshot.toObject(clazz);
                    itemList.add(item);
                    Log.i(TAG, "snapshot is "+snapshot.getId());
                }
                setValue((T) itemList);
            }
        }
    };

    @Override
    protected void onActive() {
        super.onActive();
        registration = colRef.addSnapshotListener(eventListener);
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        if (!hasActiveObservers()) {
            registration.remove();
            registration = null;
        }
    }
}

接下来,我们在存储库中创建一个链接

public class Repository {

    public Repository() {
    }

    public LiveData<List<ProductsObject>> productListening(GroupObject group) {
        return new FirestoreLiveData<>(DatabaseRouter.getCollectionRef(group.getGroupCreator()).document(group.getGroupKey()).collection("ProductList"), ProductsObject.class);
    }

}

之后,我们创建viewmodel:

public class MyViewModel extends ViewModel {

    Repository repository = new Repository();

    public LiveData<List<ProductsObject>> getProductList(GroupObject groupObject) {
        return repository.productListening(groupObject);
    }

}

最后,在我们的mainactivityfragment中,我们观察到包含在ou FireStore中的数据:

    viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
    viewModel.getProductList(groupObject).observe(this, new Observer<List<ProductsObject>>() {
        @Override
        public void onChanged(@Nullable List<ProductsObject> productsObjects) {
            //Log.i(TAG, "viewModel: productsObjects is "+productsObjects.get(0).getCode());
            adapter.submitList(productsObjects);
        }
    });

希望有帮助。

 类似资料:
  • 在我的应用程序中,我使用ViewModels为视图提供数据,数据存储库为viewmodel提供数据,并处理与数据源(如数据库、internet API和首选项)的通信。 现在android使用特殊的片段来处理设置。这些特殊片段通过直接写入SharedPreferences来处理设置数据。因此它们不符合MVVM体系结构。我还从API中读取数据,从中提取一些初始设置数据并将其保存在自己的Prefere

  • 我正在尝试从cloud Firestore的Flutter中的以下路径获取数据,我有以下结构 followers/{currentuser}/userfollower/{user_id} 用户/user_id/user_details 我正在尝试获取当前用户的所有关注者的详细信息。有人能帮忙吗? 我能得到第一部分是因为 我不知道如何循环通过所有id从用户集合中获取数据。我尝试了以下代码,但没有成功

  • 我正在开发一个应用程序,有一个标签布局作为图像。 我想使用MVVM体系结构和数据绑定库,但我对这个框架是新的。 我可以在不使用MVVM的情况下,通过使用ViewPager设置选项卡布局来完成此操作。 没有MVVM和数据绑定的普通选项卡布局: activity_main.xml: mainactivity.java: MVVM中的选项卡布局: 当将MVVM与数据绑定库一起使用时,我们将不得不为选项卡

  • 我是WPF和MVVM的新手。这是我通常为ASP.NET应用程序设置体系结构的方式: 数据层 我通常使用ORM工具将数据持久化到数据库中。 业务层 这包括我所有的商业模式和商业逻辑。 服务层 这一层用作进入后端系统的入口点。(有时通过周转基金)。这一层负责将业务模型转换为视图模型。 表示层 这一层用于表示逻辑。 我知道MVVM的视图是.xaml文件并驻留在WPF应用程序中。但是,我对“模型”和“Vi

  • Ceph 独一无二地用统一的系统提供了对象、块、和文件存储功能,它可靠性高、管理简便、并且是自由软件。 Ceph 的强大足以改变贵公司的 IT 基础架构、和管理海量数据的能力。Ceph 可提供极大的伸缩性——供成千用户访问 PB 乃至 EB 级的数据。 Ceph 节点以普通硬件和智能守护进程作为支撑点, Ceph 存储集群组织起了大量节点,它们之间靠相互通讯来复制数据、并动态地重分布数据。 Cep

  • 问题内容: 鉴于下表 我要执行以下操作: 如果我搜索Ben,我想找到图像,如果没有图像,我想找到父母的图像,如果不存在,我想转到祖父母的图像…直到点击默认图片。 最有效的方法是什么?我知道SQL并不是真正为分层值设计的,但这是我需要做的。 干杯! 问题答案: MySQL缺少递归查询,而递归查询是标准SQL的一部分。许多其他品牌的数据库都支持此功能,包括PostgreSQL(请参阅http://ww