Search code examples
androidfirebasefirebase-realtime-databasefirebaseui

FirebaseRecyclerAdapter add a hasChild() method?


Here's my database:

Database:{
  X:{
     JK-KDUKSIDKSIIJDSL1:{
        text:"hello",
        name:"Donald J. Drunk"
     }
     JK-KDadDFDDIJDSL1:{
        name:"Killery Hlinton"
     }
  }
}

And I want to filter my FirebaseRecyclerAdapter such that only add to my RecyclerView data that contains the key text. How is this possible? How can I add it? Current code:

mAdapter = new FirebaseRecyclerAdapter<Campaign, CampaignHolder>(Campaign.class, R.layout.recyclerview_template, CampaignHolder.class, ref) {
        @Override
        public void populateViewHolder(final CampaignHolder viewHolder, final Campaign campaign, final int position) {
            findViewById(R.id.progress_bar).setVisibility(View.INVISIBLE);
            MainActivity.this.holder = viewHolder;
            viewHolder.setTitle(campaign.title);
            //... Other "set" methods
    }
}

Solution

  • You could try overriding the onBindViewHolder method in your FirebaseRecyclerAdapter. Something like this:

    mAdapter = new FirebaseRecyclerAdapter<Campaign, CampaignHolder>(Campaign.class, R.layout.recyclerview_template, CampaignHolder.class, ref) {
    
                @Override
                public void onBindViewHolder(CampaignHolder viewHolder, int position) {
                    Campaign model = getItem(position);
                    if(model.getText() != null){
                        populateViewHolder(viewHolder, model, position);
                    }
                }
    
    
                @Override
                public void populateViewHolder(final CampaignHolder viewHolder, final Campaign campaign, final int position) {
                    findViewById(R.id.progress_bar).setVisibility(View.INVISIBLE);
                    MainActivity.this.holder = viewHolder;
                    viewHolder.setTitle(campaign.title);
                    //... Other "set" methods
                }
        };
    

    With this approach you would still pull all data at the query location but entries without a text attribute just wouldn't be displayed. If that is unsatisfactory and you want to minimize the amount of data you download per query then the only other option I see is closer to what is mentioned in the comments above - meaning you would need to create a separate location that only stores those entries which have a text value.