Skip to content
Advertisement

How do I display child of child’s data from firebase in my RecyclerView?

I want to show data of all children inside all the Categories from the database (added the image below of what my database looks). I am adding data to my RecyclerView using the adapter which needs FirebaseRecyclerOptions object to be passed. I saw one answer where DataSnapshot was used to get child of child data, I tried to get the data using that and it showed me when I logged it in logcat (the commented code is what I tried using), but I do not know how to use that with my Adapter class.

This is what my database looks, I want the data inside of the highlighted fields:

{
    "Category_wise": {
        "education": {
            "udemy": {     <-Return data of this child
                "companyName": "Udemy",
                ...
            },
            "khanacademy": {     <-Return data of this child
                "companyName": "Khan Academy",
                ...
            }
        },
        "technology": {
            "google": {    <-Return data of this child
                "companyName": "Google",
                ...
            },
            "facebook": {    <-Return data of this child
                "companyName": "Facebook",
                ...
            },
        ....
    }   
}

In the below code, SCard is my Model Class and SCardAdapter is my Adapter Class.

This is my Fragment (HomeFragment) where I’m adding data into recyclerview:

public class HomeFragment extends Fragment{
    private RecyclerView recyclerView;
    private Query query;
    private SCardAdapter<SCard, SCardAdapter.ViewHolder> adapter;

    public HomeFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home, container, false);
        recyclerView = v.findViewById(R.id.search_recyclerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setHasFixedSize(true);

        setQueryByOrder("technology", "totalInvestors");
        fetchResult(query);

        return v;
    }

//    protected void fetchAll(){
//        final DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Category_wise");
//        reference.addValueEventListener(new ValueEventListener() {
//            @Override
//            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
//                    Log.i(TAG, "4321: Name of each company: " + Objects.requireNonNull(snapshot.child("companyName").getValue()).toString()
//                }
//            }
//            @Override
//            public void onCancelled(@NonNull DatabaseError databaseError) {}
//        });
//    }

    protected void setQueryByOrder(String choice, String order){
        query = FirebaseDatabase.getInstance()
                .getReference()
                .child("Category_wise").child(choice).orderByChild(order);
    }

    protected void fetchResult(Query query) {
        FirebaseRecyclerOptions<SCard> options =
                new FirebaseRecyclerOptions.Builder<SCard>()
                        .setQuery(query, new SnapshotParser<SCard>() {
                            @NonNull
                            @Override
                            public SCard parseSnapshot(@NonNull DataSnapshot snapshot) {
                                return new SCard(
                                        Objects.requireNonNull(snapshot.child("companyName").getValue()).toString()...);
                            }
                        })
                        .build();
        adapter = new SCardAdapter<>(options);
        adapter.startListening();
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onStart() {
        super.onStart();
        adapter.startListening();
    }

    @Override
    public void onStop() {
        super.onStop();
        adapter.stopListening();
    }
}

This is my Adapter Class:

public class SCardAdapter<M extends SCard, V extends SCardAdapter.ViewHolder> extends FirebaseRecyclerAdapter<SCard, V> {

    FirebaseRecyclerOptions<SCard> options;
    public SCardAdapter(@Nullable FirebaseRecyclerOptions<SCard> options) {
        super(options);
        this.options = options;
    }

    @Override
    protected void onBindViewHolder(V holder, @SuppressLint("RecyclerView") final int position, SCard model) {
        holder.setName(model.getsName());
      ...
    }

    @Override
    public V onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.startup_search_card, parent, false);
        return (V) new ViewHolder(view);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView simg2;
        TextView sname, sdesc, senddate, sperraised, snoin, sminam;
        ProgressBar sraisingprogbar;
        public ViewHolder(View itemView) {
            super(itemView);
            sname = itemView.findViewById(R.id.sname);
          ...
        }

        public void setName(String string) {
            sname.setText(string);
        }
      ...
    }
}

Advertisement

Answer

First of all, you need to create 2 loops since your json looks like that and store them inside an arrayList. You are suppose to get all the data there inside the arrayList.

FirebaseDatabase.getInstance().getReference().child("Category_wise").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            ArrayList<Scard> sCardList = new ArrayList<Scard>();
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                if (snapshot.exists()){
                    for (DataSnapshot shot : snapshot.getChildren()){
                        if (shot.exists()){
                            final Scard scard = shot.getValue(Scard.class);
                            if (scard != null){
                                sCardList.add(scard);
                            }
                        }
                    }
                }
            }
            final ScardAdapter scardAdapter = new ScardAdapter(sCardList);
            recyclerView.setAdapter(scardAdapter);
        }
    }
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
    }
});

Next you need to create your own adapter. You can search on Google also for more information. But you will get the point here.

public class ScardAdapter extends RecyclerView.Adapter<ScardViewHolder> {
    private ArrayList<Scard> sCardList;
    public ScardAdapter(final ArrayList<Scard> sCardList) {
        this.sCardList = sCardList;
    }
    @NonNull
    @Override
    public ScardViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.scard_item, parent, false);
        return new ScardViewHolder(view);
    }
    @Override
    public void onBindViewHolder(@NonNull final ScardViewHolder holder, final int position) {
        final Scard model = sCardList.get(position);
        holder.getTvCompanyName.setText(model.getCompanyName);
    }
    @Override
    public int getItemCount() {
        return sCardList.size();
    }
}
Advertisement