Search code examples
androidkotlindictionarymutablelist

java.util.HashMap cannot be cast to "MODEL"


I have this issue. I'm trying generate a map function with a my model PRODUCTS, but I have this error message java.util.HashMap cannot be cast to I'm getting info from Firebase. Can somebody help me? I attach my code

fun getDeliveryList(userId: String): LiveData<MutableList<Invoice>> {
        val mutableData = MutableLiveData<MutableList<Invoice>>()
        FirebaseFirestore.getInstance().collection(Constants.ENVIRONMENT).document("users").collection("users").document(userId).collection("invoices").get().addOnSuccessListener { result ->
            val invoices = mutableListOf<Invoice>()
            for(document in result) {
                val uuid = document.getString("uuid")
                val invoiceURL = document.getString("invoiceURL")
                val products = document.get("products") as MutableList<Product>
                val createdAt = document.getString("createdAt")
                val isSponsor = document.getString("isSponsor")
                val invoice = Invoice(uuid!!, invoiceURL!!, products, createdAt!!, isSponsor!!)
                invoices.add(invoice)
            }
            mutableData.value = invoices
        }
        return mutableData
    }

I'm trying convert. to ListArray and Array


Solution

  • As per the code I can understand that all but one of the param is an Array which is the products itself.

    So we will have to ensure that it is casted correctly. We will use generic List type for Products to be safe.

    val products = data["products"] as List<*>
    

    Then afterwards we can iterate through this generic list:

     val pList = (prod as List<Map<String, Any>>).map { it ->
            Product(it["productName"] as String, it["productive"] as Double)
         }