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 = "")
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
Rayen Kamta
  • 115
  • 1
  • 2
  • 9

1 Answers1

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)
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68