0

比方說,我有這樣的:如何讓Firebase從push()鍵中獲取數據?

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

和一堆其他UNIQUE_ID S的,我想要檢索標題和描述,並把它們放在一個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所以你的downvote是值得的,並幫助社區。

回答

1

Campaign類將需要或者制定者(除了你已經擁有的干將):

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自動填充數據。

+0

但等待,在我的ViewHolder中我有setter。這有什麼不同嗎? –

+0

而且,如果我正在實施你的第二種方法,我是否還要打電話給'Campaign(title,description)'? –

+0

你不需要做任何事情,firebase-ui自動爲你映射,然後作爲'populateViewHolder()'方法中的一個參數傳遞它@AbAppletic – Wilik

相關問題