问题描述
我正在尝试从Firebase检索数据,但是我得到了:
I'm trying to retrieve data from firebase, but I get:
我不知道演员为什么会失败:
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
}
}
})
}
为什么不能将值 UsuarioFireBase.value
强制转换为 Usuario
?
Why can't I cast the value UsuarioFireBase.value
to Usuario
?
推荐答案
据我所知,您的 UsuariosFirebase.value
返回 Map< String,Object>
,确实无法将其强制转换为 Usuario
,如错误所指示.
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.
要以 Usuario
对象的形式从 DataSnapshot
中获取数据,您必须告诉Firebase为您执行该转换:
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>())
另请参阅从Firebase获取值a>.
上述内容要求您具有 Kotlin扩展(KTX)已安装Firebase实时数据库.如果您很难完成这项工作,也可以使用此变体,它是对Java代码的直接重写:
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))
这篇关于使用KOTLIN从Firebase检索数据时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!