如何从Firebase的实时数据库中获取阵列

时间:2018-09-23 01:49:48

标签: android firebase arraylist firebase-realtime-database kotlin

Product类为:

时,我想从此Firebase数据库(下图)将数据获取到ArrayListOf 中。
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的数组列表 任何帮助表示赞赏:)

firebase-database

2 个答案:

答案 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();
    }
}

一些注意事项:

答案 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错误