Firebase与Kotlin数组的评级问题

piv4azn7  于 2023-11-21  发布在  Kotlin
关注(0)|答案(1)|浏览(116)

我不能同时得到所有的评级和平均值!有人知道如何做到这一点吗?得到一个问题说“没有以下函数可以与提供的参数调用”

val ref = FirebaseDatabase.getInstance().getReference("recipes/$id/reci_ratings/")
    ref.addListenerForSingleValueEvent(object : ValueEventListener {
        override fun onDataChange(p0: DataSnapshot) {
            p0.children.forEach{
                val rt= it.child("rating").value
                val numbers = arrayOf(rt)
                var sum = 0
                for (element in numbers) {
                    sum += element
                }
                val average = sum / numbers.size
            }
        }

字符串

f0brbegy

f0brbegy1#

您的代码似乎缺少带括号的结束括号,但也许您只是错过了在问题中添加它?
另一件事是,你的numbers数组永远不会包含多个ratings值。你应该像这样声明和填充它:

val ref = FirebaseDatabase.getInstance().getReference("recipes/$id/reci_ratings/")
var numbers: ArrayList<Int> = arrayListOf() // Change to whatever type is accurate in your case
var sum = 0

ref.addListenerForSingleValueEvent(object : ValueEventListener {
    override fun onDataChange(p0: DataSnapshot) {
        p0.children.forEach {
            val rt = it.child("rating").value
            numbers.add(rt)
            
        }

        // After the forEach loop is finished you should have all the ratings in the numbers array
        
    }
})

字符串

相关问题