如何使用ArrayList <customclass>将来自Firebase的数据添加到回收站中

时间:2018-12-17 14:09:48

标签: android arraylist kotlin android-recyclerview recycler-adapter

编辑:已解决(RecyclerView shows just one item from Firebase

当前,我的代码能够从firebase中检索数据并将其放入ArrayList中。但是问题是,它只能将一个数据放入ArrayList并将其传递给回收视图适配器。

我的代码从Firebase获取并将数据填充到ArrayList

var paramType = typeof (string);
var myMiscType = typeof (MyGeneric<>).MakeGenericType(paramType);

var assembly = myMiscType.Assembly;
//my type is not in here:
var allTypesfromMyTypeAssembly = (
        from t in assembly.GetTypes()where typeof (Abase).IsAssignableFrom(t)select t);

这是我的适配器

    private fun getFromFirebase() {
        val currentUserUID = FirebaseAuth.getInstance().uid.toString()
        val ref = FirebaseDatabase.getInstance().reference
        ref.child("users").child(currentUserUID).child("foods").addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onCancelled(p0: DatabaseError) {

            }

            override fun onDataChange(p0: DataSnapshot) {
                setHasFixedSize(true)
                recyclerview.layoutManager = LinearLayoutManager(this@FoodListActivity)
                p0.children.forEach {
                    Log.d("getFood", it.toString())
                    val foodData = it.getValue(Foods::class.java)
                    if (foodData != null) {
                        val foodList = ArrayList<Foods>()
                        val adapter = ListAdapter(foodList)
                        foodList.add(foodData)
                        recyclerview.adapter = adapter

                    }
                }

            }

        })}}

这里的问题是当我执行Log.d(“ getFood”,it.toString())时,我可以从数据库中获取所有项目,但是当我执行Log.d(“ getFood”,food.size.toString ())我只会得到1,并且在我的recyclerView上,它也只会出现一个项目,每次碰巧是数据结构中的第二个项目,即“轻度辛辣”项目。

Here's my Firebase Data Structure

1 个答案:

答案 0 :(得分:0)

addListenerForSingleValueEvent更改为ValueEventListener 您还必须在此行adapter.notifydatasetchanged之后致电recyclerview.adapter = adapter

private fun getFromFirebase() {
    val currentUserUID = FirebaseAuth.getInstance().uid.toString()
    val ref = FirebaseDatabase.getInstance().reference
    ref.child("users").child(currentUserUID).child("foods").addValueEventListener(object : ValueEventListener {
        override fun onCancelled(p0: DatabaseError) {

        }

        override fun onDataChange(p0: DataSnapshot) {
            setHasFixedSize(true)
            recyclerview.layoutManager = LinearLayoutManager(this@FoodListActivity)
            p0.children.forEach {
                Log.d("getFood", it.toString())
                val foodData = it.getValue(Foods::class.java)
                if (foodData != null) {
                    val foodList = ArrayList<Foods>()
                    val adapter = ListAdapter(foodList)
                    foodList.add(foodData)
                    recyclerview.adapter = adapter
                    recyclerview.adapter.notifydatasetchanged
                }
            }

        }

    })}