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


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>() {
        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>() {
        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

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


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 :

And this tutorial :

Leave a Reply

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