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

时间:2019-01-31 18:08:53

标签: java android firebase mvvm google-cloud-firestore

我试图按照Android的架构原则,愿您实现他们对我公司的FireStore数据库之上。

目前我有一个存储区textarea,它处理所有我的查询与底层数据。我有一个Class,需要一个Fragment从文档中的域密钥的,我想知道什么是最好的方式来取回这些数据。在我以前的question Alex Mamo中,建议结合使用Set<String>Interface,因为从Firestore检索数据是onCompleteListener

这种方法似乎有效,但是我不确定如何从Asynchronous提取数据到Interface本地变量。如果我想使用这些数据,我的代码是否必须在Fragment方法的定义之内?

我还在以下MVVM原则如果从公司的FireStore数据到达我abstract我必须通过一个Fragment在一个片段定义的对象作为参数传递给我的资料库?

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

下面是我的Interface和方法,其在呼叫Interface,以检索数据:

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数据库:

query

编辑

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.");
}

1 个答案:

答案 0 :(得分:0)

例如,我仅使用interface而不是LiveData将数据带到回收站视图。

首先,我们必须创建我们的Firestore query。在此示例中,我列出了集合中的所有文档。

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;
        }
    }
}

接下来,我们在Repository

中创建一个链接
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中,我们观察到了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);
        }
    });

希望对您有帮助。