Although Firebase Realtime database can store arrays, it does not support querying array members or updating single array elements. So to solve this, I recommend you an alternative database structure that looks like this:
{
"Receptes" : {
"Ingridients" : {
"Carrot" : true,
"Salt" : true,
"Apples" : true
},
"Name" : "Food"
}
}
As you can see, now the Receptes
and the Ingridients
are stored as a Maps
and not as an arrays. And to query your database to display all ingridients, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ingridientsRef = rootRef.child("Receptes").child("Ingridients");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String ingridient = ds.getKey();
Log.d("TAG", ingridient);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
ingridientsRef.addListenerForSingleValueEvent(valueEventListener);
According to your comment, the database should look like this:
{
"Receptes" : {
"Ingridients" : {
"IngridientIdOne" : {
"Carrot" : true,
"Salt" : true,
"Apples" : true
},
"IngridientIdTwo" : {
"Strawberries" : true,
"Sugar" : true,
"Bananas" : true
},
},
"Name" : "Food"
}
}