问题
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]
回答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.
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")));
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>
.
来源:https://stackoverflow.com/questions/56320635/how-can-i-loop-over-the-items-in-the-cart-2-add-each-item-to-the-new-location