简体   繁体   中英

How to retrieve nested objects in firebase data

I'm trying to retrive data as in the next photo

在此处输入图片说明

and here's what o got from Firebase Documentation

mCoursesChild.child("Courses").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot data : dataSnapshot.getChildren()) {
              Course temp = data.getValue(Course.class);
            courses.add(temp));
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
    }
});

and "courses" is defined as ArrayList

ArrayList<Course> courses = new ArrayList<>();

and here's the Course class

public class Course {

    private String mCourseName;
    List<Subject> mSubjects;

    public Course(){}       // Default constructor required for calls to DataSnapshot.getValue(Course.class)

    public Course(String CourseName){
        mCourseName = CourseName;
    }

    public String getcourseName(){
        return mCourseName;
    }
    public List<Subject> getSubjects(){ return mSubjects;  }

}

Obviously there's something wrong, So what is the value of data.getValue(Course.class) returns ? Or am I writing the database in a wrong form ?

PS : I'm writing the database objects manually

I see a few mismatches in your code vs the naming of the JSON properties. Firebase follow JavaBean property naming conventions, which means that this getter:

public List<Subject> getSubjects(){ return mSubjects;  }

Maps to a property named subjects . In your JSON the property is named Subjects , which does not match. To fix this problem, either spell subjects in your JSON or annotate the getter:

@PropertyName("Subjects")
public List<Subject> getSubjects(){ return mSubjects;  }

Aside from that, as Anas commented: the Firebase documentation and experts recommend keeping your data structures flat by limiting each branch of your JSON to a single type.

In your case that means I'd recommend keeping three separate top-level lists:

  1. Courses
  2. Lessons
  3. Questions

If you use the same key for the lessons, you still associate the lessons with a course:

Courses
  CourseId1
    Name: "Algebra"
Lessons
  CourseId1
    LessonId1
      Name: "Algebra week 1"

This will make it much easier to:

  • Read only the data you need.
  • Ensure users can only access data they're authorized to.

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