Home > database >  Error retrieving a list of data from firebase firestore
Error retrieving a list of data from firebase firestore

Time:04-16

I have a shopping app where i need to save a list of objects, the saving into firestorm is working fine but upon getting the data, it keeps crashing and throwing an error, if anyone could help, Thank you in advance

  • This is a screenshot of firestorm and how is data saved enter image description here
  • Error thrown
  E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.shoppingapp, PID: 2110
    java.lang.ClassCastException: java.util.HashMap cannot be cast to com.example.shoppingapp.models.CheckoutModel
 
  • This is how i'm saving data into firestore
                Map<String,Object> paymentMap = new HashMap<>();
                paymentMap.put("total",String.valueOf(itemsTotal));
                paymentMap.put("items",list);

                firebaseFirestore
                        .collection("Orders")
                        .document(uniqueID)
                        .set(paymentMap)
 
  • This is how i'm trying to retrieve data
   firebaseFirestore
                .collection("Orders")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        for(DocumentSnapshot document : task.getResult()){
                            List<CheckoutModel> map = (List<CheckoutModel>) document.get("items");
                            String totalPrice = document.get("total").toString();

                            // TESTING BY GETTING PRODUCT ID
                            // it throws exception here
                            textView.setText(map.get(0).getProductID());
                        }
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {

                    }
                });

CodePudding user response:

Two things can be done,

  1. Instead of mapping the whole list, try iterating through document and map one object at a time.
  2. Secondly, In your checkOutModel give initial values to all of your variables. Mapping gives error if variables does not have initial values. Like, instantiate string variables with " ", and numeric variable with 0 or 1.
  • Related