I am using Firebase Realtime database
in my Android app. How can I query field Ingridients
in my database and get all meanings in ArrayList
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"
}
}
DatabaseReference recept = FirebaseDatabase.getInstance().getReference("Receptes");
DatabaseReference vegies = recept.child("Ingridients");
Check the documentation for more explanation.
You also need to add a listener
recept.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, dataSnapshot.child("Ingredients").getValue(String.class);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});