Retrieve an ArrayList from Firebase

I have an ArrayList of Objects in Firebase and I would like to retreive it. I have 2 array lists. One String and one Grade. When I try to use the array of objects it has a problem:

java.lang.ClassCastException: java.util.HashMap cannot be cast to com.example.gradecalculator.Grade

mDocRef:

private DocumentReference mDocRef = FirebaseFirestore.getInstance().document("myData/Arrays");

Uploading the arrays:

    Map<String, Object> dataToSave = new HashMap<String, Object>();
    dataToSave.put("StringsArray", stringGrades); // Save Strings Array
    dataToSave.put("ObjectsArray", grades); // Save Objects Array
    mDocRef.set(dataToSave).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "Document has been saved!");
            Toast.makeText(getApplicationContext(), "List has been saved successfully!", Toast.LENGTH_SHORT).show();

Downloading the arrays:

        mDocRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {
            isListEmpty = false;
            if (documentSnapshot.exists()) {
                Map<String, Object> dataToLoad = (HashMap<String, Object>) documentSnapshot.getData();
                stringGrades = (ArrayList<String>) dataToLoad.get("StringsArray");
                grades = (ArrayList<Grade>) dataToLoad.get("ObjectsArray");

                for (Grade grade : grades) {    // <------------Fails here
                    System.out.println(grade.toString());
                }

First time I’m trying to use Firebase. It seems that it saves the data in the server successfully. Any advice?

Answer

The get method of DocumentSnapshot return a List of Map :

List<Map<String, Object>>

You can create another class with your List :

  class GradeContainer{
      private List<Grade> grades;

      public GradeContainer(){}
      
      public List<Grade> getGrades(){
          return grades;
      }
    }

And use dataToLoad.toObject() :

grades = List<Grade> dataToLoad.toObject(GradeContainer.class).getGrades();

You can read this documentation for more informations :

https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/DocumentSnapshot?hl=en

And this tutorial :

https://medium.com/firebase-tips-tricks/how-to-map-an-array-of-objects-from-cloud-firestore-to-a-list-of-objects-122e579eae10

Leave a Reply

Your email address will not be published. Required fields are marked *