0

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?

3
  • what is the type of listaUsuarios? Commented Jul 6, 2020 at 10:57
  • Please edit your question and add your database structure as a screenshot. Please respond with @AlexMamo Commented Jul 6, 2020 at 11:02
  • Seems to be the same case. stackoverflow.com/questions/46957319/… Commented Feb 18, 2021 at 9:32

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

3 Comments

no type arguments expected for fun getValue: Any? ... im gonna cry
Can you try listaUsuarios.add(UsuariosFirebase.getValue(Usuario::class.java))? That's what I've seen used elsewhere, but my answer is based on what the documentation suggest.
yes, ty bro, UsuariosFirebase.getValue(Usuario::class.java) works fine :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.