获取FirebaseDatabse值

时间:2019-11-27 01:52:59

标签: android firebase kotlin firebase-realtime-database

我是Firebase的新手,我不知道如何获取下图中的分数值(通过推送和auth ID),我一直在尝试解决此问题,但应用程序崩溃了,有人可以告诉我我如何获得分数值?请

    val view: View = inflater.inflate(R.layout.fragment_classes, container, false)

    mAuth = FirebaseAuth.getInstance()
    var myRef = database?.getReference("Users")

    myRef?.child(mAuth?.currentUser!!.uid)?.addValueEventListener(object: ValueEventListener {
            override fun onDataChange(p0: DataSnapshot) {
                val score = p0.child("score")
                Toast.makeText((context as AppCompatActivity).applicationContext, score.toString(), Toast.LENGTH_SHORT).show()
            }

            override fun onCancelled(p0: DatabaseError) {
                Toast.makeText((context as AppCompatActivity).applicationContext, p0.message.toString(), Toast.LENGTH_SHORT).show()
            }
        })


    return view

2 个答案:

答案 0 :(得分:0)

您的DataSnapshot可以有多个子节点,因此您需要遍历p0.children以获取每个单独的子节点。

myRef?.child(mAuth?.currentUser!!.uid)?.addValueEventListener(object: ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            snapshot?.children?.forEach {
                val score = it.child("score")
                Toast.makeText((context as AppCompatActivity).applicationContext, score.toString(), Toast.LENGTH_SHORT).show()
            }
        }

此处使用的it是对forEach循环中当前子级的引用。

答案 1 :(得分:0)

这是我的答案,应该可以。

myRef?.child(mAuth?.currentUser!!.uid)?.addValueEventListener(object: ValueEventListener {
            override fun onDataChange(p0: DataSnapshot) {
                //val score = p0.child("score")
                snapshot?.children?.forEach { // loop for nodes
                val map = dataSnapshot.value as HashMap<String, Any>?
                    if(map!!.containsKey("score")){ // check weathrer score variable is contains
                       var score = map["score"]
                       //break :- if you do not want any oporation 
                    }
                    Toast.makeText((context as AppCompatActivity).applicationContext, score.toString(), Toast.LENGTH_SHORT).show()
                    }
                }

            override fun onCancelled(p0: DatabaseError) {
                Toast.makeText((context as AppCompatActivity).applicationContext, p0.message.toString(), Toast.LENGTH_SHORT).show()
            }
        })