[英]Retrieve data from firebase database with certain conditions
Good day, I am using Android studio to create a question and answer based game and I have a 2 things that I am struggling with. 美好的一天,我正在使用Android工作室创建一个基于问题和答案的游戏,我有两件事我正在努力。 I have a firebase database with the following structure:
我有一个具有以下结构的firebase数据库:
database name{
answers{
1{
answer_option_1: .....
answer_option_2: .....
answer_option_3: .....
answer_option_4: .....
}
2{
answer_option_1: .....
answer_option_2: .....
}
and so it carries on similar to the above shown structure. 因此它继续类似于上面显示的结构。 My question is regarding how I could retrieve the answer options and store them in their respective variables?
我的问题是关于如何检索答案选项并将它们存储在各自的变量中? such as:
如:
Option1 = answer_option_1
选项1 = answer_option_1
Is there a way to count the number of children under the parent, such as, it should tell me that under the parent 2, there are 2 children? 有没有办法计算父母下的孩子数量,比如,应该告诉我,在父母2下,有2个孩子?
My code for retrieving a single value is as follows: 我检索单个值的代码如下:
mDatabase.child("answers").child(num).child("answer_option_1").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Option1 = dataSnapshot.getValue().toString();
option1.setText(Option1);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
where mDatabase is the reference to my Firebase Database and num is a random value to retrieve a random question . 其中mDatabase是对我的Firebase数据库的引用, num是一个随机值,用于检索随机问题。 I have repeated the above code a 4 times for the 4 options, but when I have 2 options, as mentioned and shown in the database structure above, my app stops working.
我已经为4个选项重复了上面的代码4次,但是当我有2个选项时,如上面的数据库结构所示,我的应用程序停止工作。
All help will be highly appreciated. 所有帮助将受到高度赞赏。
I'm still not getting why do you want to count the children but you might be interested in using ChildEventListener
to get a callback for each child inside /answers/num
. 我仍然没有得到你为什么要计算孩子,但你可能有兴趣使用
ChildEventListener
来获取/answers/num
每个孩子的回调。
Set a list that will track the options: 设置一个跟踪选项的列表:
List<String> options = new ArrayList<>();
And when loading the view or whatever make sure you start the listener: 在加载视图或其他任何内容时确保启动监听器:
mDatabase.child("answers").child(num).addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot) {
String option = dataSnapshot.getValue().toString();
options.add(option);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.