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

How to make Firebase get data from inside push() keys?

假设我有这个:

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

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


我试过的:

我尝试使用字符串 descriptiontitle.

制作自定义广告系列 class

我有这个方法:

 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 class 将需要 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;
    }

}

或者,只需创建字段 public 并删除 getters/setters:

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

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