我正在尝试遵循 Android 架构原则,并希望您在我的 FireStore 数据库之上实现它们。
目前我有一个存储库 Class
处理我对底层数据的所有查询。我有一个 Fragment
这需要 Set<String>
文档字段中的键,想知道检索此数据的最佳方法是什么。在我之前的question Alex Mamo建议使用 Interface
结合 onCompleteListener
因为从 Firestore 检索数据是 Asynchronous
.
这种方法似乎可行,但我不确定如何从此 Interface
中提取数据到我的本地变量 Fragment
.如果我想使用这些数据,我的代码必须在我对 abstract
的定义范围内吗?方法?
如果要将数据从 Firestore 获取到我的 Fragment
,我是否仍然遵循 MVVM 原则?我必须通过 Interface
fragment 中定义的对象作为我存储库的参数?
这是使用存储库查询 Firestore 数据库的推荐方法吗?
下面是我的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);
}
最后我的 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 查询
。在此示例中,我列出了集合中的所有文档。
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);
}
}
最后,在我们的 MainActivity
或 Fragment
中,我们观察到 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);
}
});
希望对你有帮助。
关于java - 使用 MVVM 架构从 FireStore 检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54466799/