编辑:已解决(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上,它也只会出现一个项目,每次碰巧是数据结构中的第二个项目,即“轻度辛辣”项目。
答案 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
}
}
}
})}