Search code examples
firebasekotlinarraylistgoogle-cloud-firestorehashmap

Cannot get hash map value as ArrayList


I have a data class called Product and its object are stored in an ArrayList.

Then I am creating an hashmap val prodInCartMap: HashMap<String, ArrayList<Product> = HashMap()

I am adding the array list to the hash map prodInCartMap["prodInCart"] = list, where list is val list: ArrayList<Product> = ArrayList()

Then I am uploading the data to Cloud Firestore.

When I am getting the data this is the code:

fun getHashMapActivity(uid: String, activity: CartActivity){
        FirebaseFirestore.getInstance().collection(Constants.CART_COLLECTION)
            .document(uid)
            .get()
            .addOnSuccessListener {
                val map: HashMap<String, Any> = it.data as HashMap<String, ArrayList<Product>>
                val temp = map["prodInCart"] as ArrayList<Product>
                for (i in temp.indices){
                     val product: Product = temp[i] as Product
                }
            }
    }

While executing the for loop I get this error:

java.lang.ClassCastException: java.util.HashMap cannot be cast to com.example.grocerystore.models.Product

Why is it still a hash map even after converting it into ArrayList?

Here is the screenshot of my database:

Firebase

Whenever I hover my mouse over: val cart: HashMap<String, ArrayList<Product>> = it.data as HashMap<String, ArrayList<Product>>

I get this warning:

Unchecked cast: (Mutable)Map<String!, Any!>? to kotlin.collections.HashMap<String, ArrayList /* = ArrayList /> / = java.util.HashMap<String, ArrayList> */

Firebase

My product class:

data class Product(
        var prod_name: String = "",
        var prod_image: Int = -1,
        var prod_desc: String = "",
        var prod_price: Int = -1,
        var prod_tags: ArrayList<String> = ArrayList(),
        var kgOrPack: Boolean = true //true: pack, false: kg
): Serializable

Solution

  • You are getting the following error:

    java.lang.ClassCastException: java.util.HashMap cannot be cast to com.example.grocerystore.models.Product

    Because you are trying to loop through an ArrayList that contains "HashMap" objects and not "Product" objects. Since there is no inheritance relationship between these classes, the cast is actually not possible, hence the error. There are two ways in which you can solve this.

    The hard way is to iterate the HashMap objects and create "Product" objects yourself, or, the easy way is to map the array of Product objects into a List as explained in the following article:

    How to map an array of objects from Cloud Firestore to a List of objects?