eva*_*als 2 android arraylist kotlin firebase firebase-realtime-database
我想从这个 firebase-database(下图)获取数据到一个 ArrayListOf< Product> 当Productclass 是:
data class Product(
val title:String,
val photoURL:String,
val description:String,
val price:Double
)
//and i want to make an array like this
val r = arrayListOf<Product>()
Run Code Online (Sandbox Code Playgroud)
所以基本上我想制作 Firebase_Database_products 的数组列表,感谢任何帮助:)
只是为了将来的读者,这里是 Kotlin 中所需的代码:
val products = arrayListOf<Product>()
val ref = FirebaseDatabase.getInstance().getReference("products")
ref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (productSnapshot in dataSnapshot.children) {
val product = productSnapshot.getValue(Product::class.java)
products.add(product!!)
}
System.out.println(products)
}
override fun onCancelled(databaseError: DatabaseError) {
throw databaseError.toException()
}
})
}
Run Code Online (Sandbox Code Playgroud)
并且您必须像这样在 Product 类中初始化变量:
data class Product(
val title:String = "",
val photo:String = "",
val description:String = "",
val price:Double = -1.0
)
Run Code Online (Sandbox Code Playgroud)
如果你没有初始化就离开它,你会得到class does not define a no-argument constructor错误
| 归档时间: |
|
| 查看次数: |
5011 次 |
| 最近记录: |