如何遍历购物车中的物品,2)将每个物品添加到新位置,3)从旧位置删除物品 [英] How can I loop over the items in the cart, 2) Add each item to the new location, 3) Delete the item from the old location
问题描述
正在使用Recycler firestore Adapter显示项目.我希望将recyclerview视图中的项目添加到另一个数据库中,并通过单击按钮清除初始数据库.我尝试了此操作,但出现了一个错误,即com.google.firebase.firestore.QuerySnapshot无法转换为java.util.List
The items are being displayed using Recycler firestore Adapter. I want to have the items in the recyclerview view to be added in another database and the initial database cleared by a click of a button. I tried this but I got the error that com.google.firebase.firestore.QuerySnapshot cannot be cast to java.util.List
public void placeOrder() {
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query query = rootRef
.collection(String.valueOf(new
StringBuffer("/").append(user.getUid()).append("cart")));
Task task = query.get();
task.addOnSuccessListener(new OnSuccessListener<List<Object>>() {
@Override
public void onSuccess(List<Object> list) {
CollectionReference notebookRef;
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
if (user != null) {
notebookRef = db.collection(String.valueOf(new
StringBuffer("/").append(user.getUid()).append("order")));
String name = String.valueOf(list.get(1));
String delivery = String.valueOf(list.get(2));
String amount = String.valueOf(list.get(3));
OrderItem orderItem = new OrderItem(name, amount,
delivery);
notebookRef.add(orderItem);
Toast.makeText(context, "Items Added",
Toast.LENGTH_SHORT).show();
}
}
});
}[![This is my Database][1]][1]
推荐答案
The Query.get()
method returns a Task<QuerySnapshot>
. Since you declared a Task<List>
in your code, this results in the error that you get: com.google.firebase.firestore.QuerySnapshot cannot be cast to java.util.List
.
请阅读从集合中读取多个文档的文档,因为它包含您需要的精确代码段.
Please study the documentation on reading multiple documents from a collection, as it contains the precise code snippet you need.
尽管您要从一个集合中获取整个集合还是单个文档,但我还是不能完全确定.您可以这样初始化query
:
One thing I'm not completely sure of though it whether you are getting an entire collection or a single document from a collection. You initialize query
like this:
Query query = rootRef.collection(
String.valueOf(new StringBuffer("/").append(user.getUid()).append("cart")));
据我所知,这导致了"/uidOfUser/cart"
的路径,该路径将指向以当前用户命名的集合中的cart
文档.如果确实是您的数据库结构,则需要遵循获取单个文档,该文档将返回Task<DocumentSnapshot>
.
As far as I can see this leads to a path of "/uidOfUser/cart"
, which would point to the cart
document in a collection named after the current user. If that is indeed your database structure, you'll need to follow the example from the documentation on getting a single document, which returns a Task<DocumentSnapshot>
.
这篇关于如何遍历购物车中的物品,2)将每个物品添加到新位置,3)从旧位置删除物品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!