How to access data from firebase Realtime database child?

Realtime Database Data

My realtime database json

 "module1" : {
"Operating System" : {
  "pdfName" : "pdf",
  "pdfUrl" : "gs://knec-pastpapers.appspot.com/module1/OS/july2007.pdf"
}

}

I have a problem accessing the fields under Operating System and display the data in Recycler view. This is my model class

public class viewModel {
public String pdfName;
public String pdfUrl;


public viewModel() {

}

public viewModel(String pdfName, String pdfUrl) {
    this.pdfName = pdfName;
    this.pdfUrl=pdfUrl;
}


public String getPdfName() {
    return pdfName;
}

public void setPdfName(String pdfName) {
    this.pdfName = pdfName;
}

public String getPdfUrl() {
    return pdfUrl;
}

public void setPdfUrl(String pdfUrl) {
    this.pdfUrl = pdfUrl;
}

This is how i am trying to access the fields from realtime database

databaseReference= FirebaseDatabase.getInstance().getReference("ict").child("Operating System");
    getImageData();
}

private void getImageData() {
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            for (DataSnapshot di:dataSnapshot.getChildren()){
                viewModel articleList=di.getValue(viewModel.class);
                articleLists.add(articleList);
            }
            loadpdfsAdapter adapter=new loadpdfsAdapter(articleLists,getApplicationContext());
            rv.setAdapter(adapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
} 

After running the code my recyclerview is empty. My question is how can i access the child nodes under Operating System?

Answer

The for (DataSnapshot di:dataSnapshot.getChildren()){ is only needed when the snapshot you get has multiple viewModel child nodes. But since you’re loading data from /ict/Operating System there is only a single viewModel child node.

You either have to remove the loop:

databaseReference= FirebaseDatabase.getInstance().getReference("ict").child("Operating System");

databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        viewModel articleList=dataSnapshot.getValue(viewModel.class);
        articleLists.add(articleList);
        ...

Or you can load all of ict and then loop over the child nodes:

databaseReference= FirebaseDatabase.getInstance().getReference("ict");

databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for (DataSnapshot di:dataSnapshot.getChildren()){
            viewModel articleList=di.getValue(viewModel.class);
            articleLists.add(articleList);
        }
        ...

Leave a Reply

Your email address will not be published. Required fields are marked *