问题描述
我在Android应用中使用 Firebase实时数据库
。如何在我的数据库中查询字段 Ingridients
并获得 ArrayList
中的所有含义?
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
?
我的数据库有结构:
{
"Receptes" : [ {
"Ingridients" : [ "Carrot", "Salt", "Apples" ],
"Name" : "Food"
} ]
}
推荐答案
虽然Firebase实时数据库可以存储数组,但它不支持查询数组成员或更新单个数组元素。因此,为了解决这个问题,我建议您使用另一种类似于此的数据库结构:
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"
}
}
如你所见,现在 Receptes
和 Ingridients
存储为地图
而不是数组。要查询数据库以显示所有ingridients,请使用以下代码:
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"
}
}
这篇关于在ArrayList中获取字段的所有含义火力地堡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!