我在处理子集合和将数据获取到android时遇到一些问题。
我的Firestore结构如下:
这是我遇到的问题:
我想要什么:检索子集合中的所有productID字段,以便在另一个查询中使用它。 我被困住了:如何真正做到这一点?我一直在跟踪所有与Firestore相关的问题,但我只是迷路了。 这是我尝试做的,是的,我正在使用RecylcerView:
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference panieref = db.collection("panier");
private CollectionReference prodref = db.collection("products");
private void setUpRecyclerView(){//for loading items from firestore
final List<List<DocumentSnapshot>> productsList=new ArrayList<>();
Query query =panieref.whereEqualTo("ID_del",newcom.getID_del());
panieref.whereEqualTo("ID_del",newcom.getID_del()).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull final Task<QuerySnapshot> task) {
if(task.isSuccessful()){
for(final QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
prodref.whereEqualTo("productID", Objects.requireNonNull(document.get("productID")).toString()).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if(task.isSuccessful()){
CollectionReference ProdColRef=panieref.document((String) Objects.requireNonNull(document.get("product_ID"))).collection("produits");
productsList.add(task.getResult().getDocuments());
}
}
});
} }
}
});
adapter= new detailsAdapter(productsList);
//call up the recyclerview from the itemlist layout into the main activity layout
RecyclerView recyclerView = findViewById(R.id.items_recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setAdapter(adapter);
}
请帮助,已经过去了一个星期,我没有取得任何进展,并且取消了很多行代码,我觉得自己没用。
答案 0 :(得分:0)
现在,您正在使用以下方式创建对产品集合的引用:
private CollectionReference prodref = db.collection("products");
这意味着Firestore会寻找顶级集合名称products
,据我所知,该名称在您的数据库中不存在。
如果要从特定的panier
文档收集产品,则需要在该特定文档上致电collection("products")
:
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference panieref = db.collection("panier");
final List<List<DocumentSnapshot>> productsList=new ArrayList<>();
Query query =panieref.whereEqualTo("ID_del",newcom.getID_del());
panieref.whereEqualTo("ID_del",newcom.getID_del()).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull final Task<QuerySnapshot> task) {
if(task.isSuccessful()){
for(final QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
CollectionReference prodref = document.getReference().collection("products");
prodref.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if(task.isSuccessful()){
productsList.add(task.getResult().getDocuments());
}
}
});
}
}
}
});