当Product
类为:
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>()
所以基本上我想创建Firebase_Database_products的数组列表 任何帮助表示赞赏:)
答案 0 :(得分:2)
类似这样的事情应该可以解决:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("products");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<Product> products = new ArrayList<Product>();
for (DataSnapshot productSnapshot: dataSnapshot.getChildren()) {
Product product = productSnapshot.getValue(Product.class);
products.add(product);
}
System.out.println(products);
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
一些注意事项:
p1
和p2
)。如果以后要修改或删除产品,则可能需要这些密钥,因此应考虑将它们存储在Product
类中。另请参阅:Is there a way to store Key in class which I cast from Firebase object? 答案 1 :(得分:1)
仅适用于以后的读者,这是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()
}
})
}
,您必须像这样在Product类中初始化变量:
data class Product(
val title:String = "",
val photo:String = "",
val description:String = "",
val price:Double = -1.0
)
如果不进行初始化就留下class does not define a no-argument constructor
错误