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

时间:2016-07-26 17:57:10

标签: android android-recyclerview firebase-realtime-database firebaseui

假设我有这个:

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

以及其他一些UNIQUE_ID,我想检索标题和说明并将它们放入RecyclerView

我尝试了什么:

我尝试使用字符串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。但是我在哪里得到这个,或者我做错了吗?

注意:如果我不清楚,我努力做到了,请告诉我在你投票之前缺少什么,这样你的downvote值得并帮助社区。

1 个答案:

答案 0 :(得分:1)

您的Campaign课程需要设置器(除了您已有的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;
    }

}

或者,只需将字段设为公开并删除getter / setter:

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

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