为什么我的RecyclerView在kotlin中重复行?

时间:2019-12-01 21:30:43

标签: android kotlin android-recyclerview

我正在检索下面链接中显示的Firebase数据。 RecyclerView显示了应排成一行的多个副本,我不知道为什么。数据库中每个部分的键应与RecyclerView中每一行的标题相同。

Fibebase数据链接1

The output of the app

使用此代码

    var benefitSpinner = benefitListSpinner

    val spinnerSelection = arrayOf("National", "Texas", "Iowa", "Alabama")

    benefitSpinner.adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, spinnerSelection)

    benefitSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
        override fun onNothingSelected(parent: AdapterView<*>?) {
            location = "National"
        }

        override fun onItemSelected(
            parent: AdapterView<*>?,
            view: View?,
            position: Int,
            id: Long
        ) {

            location = spinnerSelection.get(position)

            fetchNationalBenefits()

        }

    }

}

val benefitMap = LinkedHashMap<String, Benefit>()

private  fun refreshRecyclerViewMessages(){


    benefitMap.values.forEach{
        adapter.add(BenefitItem(it))


    }
}

private fun fetchNationalBenefits() {

    benefitMap.clear()
    adapter.clear()

    val ref = FirebaseDatabase.getInstance().getReference("/$location")
    ref.addChildEventListener(object: ChildEventListener{

        override fun onChildAdded(p0: DataSnapshot, p1: String?) {
            p0.children.forEach{
                val benefitItem = p0.getValue(Benefit::class.java) ?: return

                benefitMap[p0.key!!] = benefitItem

            }
            refreshRecyclerViewMessages()
        }

        override fun onChildChanged(p0: DataSnapshot, p1: String?) {

        }
        override fun onChildMoved(p0: DataSnapshot, p1: String?) {

        }
        override fun onChildRemoved(p0: DataSnapshot) {

        }

        override fun onCancelled(p0: DatabaseError) {

        }
    })
}

}

1 个答案:

答案 0 :(得分:0)

onChildAdded对于您的每个“ / $ location / *”项目都会被调用一次。

如果我理解您的意图正确,那么您想为每个此类项目致电adapter.add(item)。但是相反,您要调用refreshRecyclerViewMessages,每次将{em> all 从benefitMapadapter的所有项目添加到一起,并创建重复项。

要解决该问题,您必须摆脱forEach中的循环(refreshRecyclerViewMessages调用),只需将onChildAdded中的新项添加到适配器中。 / p>