如何从当前用户获取FirebaseDataBase快照?

时间:2018-11-23 21:21:25

标签: android firebase firebase-realtime-database kotlin

private fun getUserInfo() {


val userkey = FirebaseAuth.getInstance().uid ?: ""
val ref = FirebaseDatabase.getInstance().getReference("/users/$userkey")
ref.addListenerForSingleValueEvent(object: ValueEventListener {

    override fun onDataChange(p0: DataSnapshot) {
        val adapter = GroupAdapter<ViewHolder>()

        p0.children.forEach {
            Log.d("getUserInfo", it.toString())
            val user = it.getValue(User::class.java)
            if (user != null) {
                adapter.add(UserItem(user))
            }
        }

        UserInfo_RCView.adapter = adapter
    }

    override fun onCancelled(p0: DatabaseError) {

    }
})
}
}

class UserItem(val user: User): Item<ViewHolder>() {
override fun bind(viewHolder: ViewHolder, position: Int) {
    viewHolder.itemView.UsernameSettings_txt.text = user.username

    Picasso.get().load(user.profileImageUrl).into(viewHolder.itemView.ProfileImage_View)
}

override fun getLayout(): Int {
    return R.layout.userinfo
}
}

我想像这样从当前用户创建快照,每次将$userkey放入ref值时,应用都会因以下错误而崩溃:

  

2018-11-23 22:04:48.414 3871-3871 / my.app E / RecyclerView:未连接适配器;跳过布局   2018-11-23 22:04:49.797 3871-3871 / my.app E / AndroidRuntime:FATAL EXCEPTION:main       程序:nobrand.ljb.musicshare,PID:3871       com.google.firebase.database.DatabaseException:无法将类型为java.lang.String的对象转换为类型myapp.User

当我没有将$userkey放在我的参考值中时。该应用程序正常运行,可以按预期显示所有用户,但是正如我所说,我不希望那样。 我会很感激每一个答案和建议!

1 个答案:

答案 0 :(得分:1)

如果直接访问正确的子节点,则不再需要代码中的循环。

这意味着有两种简单的方法可以做到这一点:

  1. 按键查询
  2. 删除循环

我建议删除循环,因为确实不再需要它了,但是想显示两个选项。

按键查询

val ref = FirebaseDatabase.getInstance().getReference("/users")
ref.orderByKey().equalTo(userkey).addListenerForSingleValueEvent(object: ValueEventListener {

    override fun onDataChange(p0: DataSnapshot) {
        val adapter = GroupAdapter<ViewHolder>()

        p0.children.forEach {
            Log.d("getUserInfo", it.toString())
            val user = it.getValue(User::class.java)
            if (user != null) {
                adapter.add(UserItem(user))
            }
        }

        UserInfo_RCView.adapter = adapter
    }

    override fun onCancelled(p0: DatabaseError) {
        throw p0.toException();
    }
})

删除循环

val ref = FirebaseDatabase.getInstance().getReference("/users/$userkey")
ref.addListenerForSingleValueEvent(object: ValueEventListener {

    override fun onDataChange(p0: DataSnapshot) {
        val adapter = GroupAdapter<ViewHolder>()

        val user = p0.getValue(User::class.java)
        if (user != null) {
            adapter.add(UserItem(user))
        }

        UserInfo_RCView.adapter = adapter
    }

    override fun onCancelled(p0: DatabaseError) {
        throw p0.toException();
    }
})