darkblade60
darkblade60

Reputation: 1

error retrieving data from firebase with KOTLIN

I'm trying to retrieve data from firebase, but I get:

java.lang.ClassCastException: java.util.HashMap cannot be cast to com.android.mlc.model.Usuario

I don't know why the cast fails:

private fun listarDatos() {

    databaseReference.child("Usuario").addValueEventListener(object : ValueEventListener{
        override fun onCancelled(p0: DatabaseError) {
            Toast.makeText(baseContext, "Failed to load post.",
                Toast.LENGTH_SHORT).show()
        }

        override fun onDataChange(dataSnapshot: DataSnapshot) {

            Log.w("Usuarios1", "mehe")
            for (UsuariosFirebase in dataSnapshot.children) {
                  listaUsuarios.add(UsuariosFirebase.value as Usuario) <--- ERROR
      

                arrayAdapterUusuario = ArrayAdapter<Usuario>(this@MainActivity,android.R.layout.simple_list_item_1, listaUsuarios)
                listaV_Usuarios.adapter = arrayAdapterUusuario
            }


        }
    })
}

Why can't I cast the value UsuarioFireBase.value to Usuario?

Upvotes: 0

Views: 601

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599996

As far as I can see, your UsuariosFirebase.value returns a Map<String, Object>, which indeed can't be cast to Usuario as the error indicates.

To get the data from the DataSnapshot as a Usuario object, you will have to tell Firebase to do that conversion for you:

listaUsuarios.add(UsuariosFirebase.getValue<Usuario>())

Also see the documentation on getting values from Firebase.


The above requires that you have the Kotlin extensions (KTX) for Firebase Realtime Database installed. If you're having a hard time making that work, you can also use this variant, which is a pretty direct rewrite of the Java code:

listaUsuarios.add(UsuariosFirebase.getValue(Usuario::class.java))

Upvotes: 1

Related Questions