2

I want to get data from this firebase-database (the picture below) into an ArrayListOf< Product> when Product class is :

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>()

so basicly i want to make array list of Firebase_Database_products any help is appreciated :)

firebase-database

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
evals
  • 1,750
  • 2
  • 18
  • 28
  • Firebase official docs has outlined the methods to query lists in Firebase realtime-database: https://firebase.google.com/docs/database/android/lists-of-data. Also, here is a useful article outlining the storing & querying: https://medium.com/a-practical-guide-to-firebase-on-android/storing-and-retrieving-data-from-firebase-with-kotlin-on-android-91c36680771 – Neelavar Sep 23 '18 at 02:09

2 Answers2

6

just for readers in future here is the required code in 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()
            }
        })
    }

and you have to initialize variables in Product class like this :

data class Product(
val title:String = "",
val photo:String = "",
val description:String = "",
val price:Double = -1.0
)

if you leave it without initializing you will get class does not define a no-argument constructor error

evals
  • 1,750
  • 2
  • 18
  • 28
2

Something like this should do the trick:

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

A few things to note:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807