簡體   English   中英

使用MVVM體系結構從FireStore檢索數據

[英]Retrieving Data from FireStore using MVVM Architecture

我正在嘗試遵循Android體系結構原則,並希望您在FireStore數據庫的頂部實現它們。

目前,我有一個存儲庫Class ,用於處理所有帶有基礎數據的查詢。 我有一個需要從文檔中的字段中獲取鍵的Set<String>Fragment ,並且想知道檢索此數據的最佳方法是什么。 在我之前的問題中, Alex Mamo建議將InterfaceonCompleteListener結合使用,因為從Firestore檢索數據是Asynchronous

這種方法似乎有效,但是我不確定如何從此Interface提取數據到Fragment局部變量。 如果我想使用這些數據,我的代碼是否必須在我對abstract方法的定義之內?

如果要將數據從Firestore獲取到我的Fragment我是否仍要遵循MVVM原理,我必須將片段中定義的Interface對象作為參數傳遞給我的存儲庫?

這是使用存儲庫查詢Firestore數據庫的推薦方法嗎?

以下是調用ViewModel檢索數據的Interface和方法:

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

最后,我的Repository方法query我的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);
}

例如,我只使用LiveData而不是interface將數據帶到recyclerview。

首先,我們必須創建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);
        }
    });

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM