从Firebase提取数据并添加到卡片视图

时间:2019-05-22 20:03:39

标签: java android firebase android-cardview

我想从Firebase提取数据并将其添加到cardView。 当我获取标题和描述时,会显示标题,但不会显示我的描述。

这是我的模型课:

public class News {
    public String mtitle, mdesc;

    public News(){

    }

    public News(String title, String desc) {
        mtitle = title;
        mdesc = desc;
    }

    public String getTitle() {
        return mtitle;
    }

    public void setTitle(String title) {
        mtitle = title;
    }

    public String getDesc() {
        return mdesc;
    }

    public void setDesc(String desc) {
        mdesc = desc;
    }
}

这是我的控制者:

//FR options and adapter
    options = new FirebaseRecyclerOptions.Builder<News>()
            .setQuery(newsRef, News.class).build();

    adapter = new FirebaseRecyclerAdapter<News, NewsViewHolder>(options) {
        @Override
        protected void onBindViewHolder(@NonNull NewsViewHolder holder, int position, @NonNull News model) {
            holder.mtitle.setText(model.getTitle());
            holder.mdesc.setText(model.getDesc());
        }

        @NonNull
        @Override
        public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.news_row, viewGroup, false);

            return new NewsViewHolder(view);
        }
    };

    GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 1);
    mNewsList.setLayoutManager(gridLayoutManager);
    adapter.startListening();
    mNewsList.setAdapter(adapter);

这是我的Firebase结构:

image

1 个答案:

答案 0 :(得分:0)

看看@PropertyName("title") documentation。尽管它的文档缺乏详尽说明,但它表明您需要此批注来对模型对象进行(反序列化)序列化。有关更多详细信息,请参见this question

基本上,您可以使用它来将Firebase中的属性与Model类中的字段进行匹配。在您的情况下,它将变成这样(未经测试):

public class News {

    @PropertyName("title")
    public String mtitle;

    @PropertyName("description")
    public String mDesc;

    public News(String title, String desc) {
        mtitle = title;
        mdesc = desc;
    }
}

或者,当您切换到Kotlin时:

data class News(
    @set:PropertyName("title") var title: String = "",
    @set:PropertyName("description") var desc: String = "",
)