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

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.