1
votes

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. I have a firebase database with the following structure:

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

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?

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 . 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.

All help will be highly appreciated.

1
Why do you use child("answer_option_1") if you want to get all 4 answer options anyway? - Dreamcooled
I didnt get why are you concerned on counting the number of childs - adolfosrs
@adolfosrs I want to count the number of children so I can set the number of options per question. - user4696806
@PrathamPatel what do you mean by "set the number of options"? You can get this data by just getting the options array size. Let me know if u still have any doubts. - adolfosrs

1 Answers

0
votes

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.

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) {

        }
    });