【问题标题】:How to get array from Real-Time Database in Firebase如何从 Firebase 中的实时数据库中获取数组
【发布时间】:2019-02-26 23:02:33
【问题描述】:
当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 的数组列表
任何帮助表示赞赏:)
【问题讨论】:
标签:
android
firebase
arraylist
firebase-realtime-database
kotlin
【解决方案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 错误
【解决方案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();
}
}
需要注意的几点: