如何使Firebase从push()键内部获取数据



假设我有这个:

Campaigns:{
    UNIQUE_ID:{
     title: "Hello",
     description: "Desc"
  }
}

还有一堆其他的UNIQUE_ID,我想检索标题和描述,并将它们放入RecyclerView中。


我尝试了什么:

我尝试制作一个自定义的Campaign类,使用字符串descriptiontitle

我有这样的方法:

 String title;
 String description;
 public Campaign(){}
 public Campaign(String title, String description) {
    this.title = title;
    this.description = description;
}
public String getTitle() {
    return title;
}
public String getDescription() {
    return description;
}

当我尝试获得适配器时,使用此方法:

 RecyclerView.Adapter mAdapter = new FirebaseRecyclerAdapter<Campaign,CampaignHolder>(Campaign.class, R.layout.recyclerview_template, CampaignHolder.class,ref){
        @Override
        public void  populateViewHolder(CampaignHolder viewHolder, Campaign campaign, int position){
            viewHolder.setTitle(campaign.getTitle());
            viewHolder.setDescription(campaign.getDescription());
        }
    };

campaign.getTitle()显然正在返回null,我可以理解为什么,因为我从未调用过构造函数。但是,如果我想调用构造函数,我需要参数title,description。但是我从哪里得到这个,或者我做错了吗?

您的Campaign类将需要任意一个setter(除了您已经拥有的getter之外):

public class Campaign {
     String title;
     String description;
     public Campaign(){}
     public Campaign(String title, String description) {
        this.title = title;
        this.description = description;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(title) {
        this.title = title;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(description) {
        this.description = description;
    }
}

或者,只需公开字段并删除getters/ssetters:

public class Campaign {
     public String title;
     public String description;
     public Campaign(){}
     public Campaign(String title, String description) {
        this.title = title;
        this.description = description;
    }    
}

基于这些公共字段(或getters/settier),Firebase数据库客户端将根据从数据库中读取的JSON自动填充数据。

相关内容

  • 没有找到相关文章

最新更新