简体   繁体   中英

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

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

        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM