enter image description here

I want to retrieve and show Collection data saved in Firebase database on the android screen.

I get three types of information(orders, quantity, date) from the users and save them on the database using :

OrderInfo orderInfo = new OrderInfo(orderText, quantityText, dateText);
db.collection("orders").document(user.getUid()).set(orderInfo)

And now I want to retrieve all the data(orderText, quantityText, dateText) saved in collection "orders" maybe in the form of list.

How can I do that?

1 Answers

0
Alex Mamo On

To get the values of your orderText, quantityText and dateText properties within a single OrderInfo object, please use the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference ordersRef = rootRef.collection("orders");
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
ordersRef.document(uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                OrderInfo orderInfo = document.toObject(OrderInfo.class);
                Log.d(TAG, orderInfo.getOrderText() + " / " + orderInfo.getQuantityText() + " / " + orderInfo.getDateText());
            }
        }
    }
});

If you want to get all OrderInfo objects within your orders collection, please use the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference ordersRef = rootRef.collection("orders");
ordersRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            List<OrderInfo> list = new ArrayList<>();
            for (QueryDocumentSnapshot document : task.getResult()) {
                OrderInfo orderInfo = document.toObject(OrderInfo.class);
                list.add(orderInfo);
            }

            //Do what you need to do with  your list
        }
    }
});