Kotlin Android Firebase Database Hashmap Cast to Class
Asked Answered
R

1

5

I am trying to get data from a firebase database. The breakpoints show it is getting the data, but it looks like I am not properly assigning it to my class.

which causes this exception :

java.lang.ClassCastException: java.util.HashMap cannot be cast to Class

override fun onDataChange(p0: DataSnapshot?) {
    if (p0!!.exists()){
        val children = p0!!.children
        children.forEach {
            println(it.value.toString())
            var item : DashboardItem = it.value as DashboardItem
            println(item)
        }
    }
}

this is the DB export :

{
 "dashboard" : [ 
    { "name" : "News"}, 
    { "name" : "Chatroom"},
    { "name" : "Music"},
    { "name" : "Quotes"},
    { "name" : "Reminder"},
    { "name" : "Poll"},
    { "name" : "Suggestion"},
    { "name" : "LogOut"} ]  
}

the class object i want to create

data class DashboardItem(val name: String = "")
Rocco answered 26/10, 2017 at 14:43 Comment(0)
U
6

Issue : DataSnapshot#getValue() will return only native types as

Boolean
String
Long
Double
Map<String, Object> // closest to your object representation
List<Object>

where Map<String, Object> will be returned as object when requested hence the error when you apply explicit cast

So instead use DataSnapshot#getValue(Class<T> valueType) as

val item : DashboardItem = it.getValue(DashboardItem::class.java)
Unofficial answered 26/10, 2017 at 15:10 Comment(2)
THANKS Mr Singh val item : DashboardItem = it.getValue(DashboardItem::class.java)!! had to add !!Rocco
I am glad that i could help Mr. Kamta , happy codingUnofficial

© 2022 - 2024 — McMap. All rights reserved.