来自firebase数据库的数据未正确显示

时间:2017-05-01 13:13:07

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

我正在尝试从firebase数据库中检索数据,当我尝试在安装应用程序后第一次检索数据时,回收器视图中没有显示任何内容,但当我按下并再次尝试检索数据时,其显示正常,建议我更改我应该在我的代码中执行哪些操作,以便在第一次尝试时正确显示数据

用于返回ArrayList的方法

 public ArrayList<SaveAddInformation> retrieve(){

    AdvertisementRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {

                SaveAddInformation mModel = eventSnapshot.getValue(SaveAddInformation.class);
                Log.d("DATA" ,""+ mModel);
                adinfolist.add(mModel);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


    return adinfolist;

}

Adpater Class

 Context c;
ArrayList<SaveAddInformation> adinfolist;

public MyAdapter(Context c, ArrayList<SaveAddInformation> adinfolist) {
    this.c = c;
    this.adinfolist = adinfolist;
}

@Override
public MyViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v= LayoutInflater.from(c).inflate(R.layout.design_row,parent,false);
  MyViewholder myViewholder=new MyViewholder(v);

   return myViewholder;
}

@Override
public void onBindViewHolder(MyViewholder holder, int position) {
    SaveAddInformation save=adinfolist.get(position);
    holder.titleTv.setText(save.getTitleS());
    holder.rentamt.setText(save.getRent_amount());
    holder.rentdays.setText(save.getRentDayS());
    holder.desc.setText(save.getDescriptionS());

    holder.setImage(getApplicationContext(), save.getImageuri());

  //  holder.titleTv.setText((CharSequence) adinfolist.get(position));
}

@Override
public int getItemCount() {
    return adinfolist.size();
}

}

ViewHolder Class

 public MyViewholder(View itemView) {
    super(itemView);
    titleTv=(TextView)itemView.findViewById(R.id.Titletextv);

    rentamt=(TextView)itemView.findViewById(R.id.rent_amount);
    rentdays=(TextView)itemView.findViewById(R.id.days_rent);
    desc=(TextView)itemView.findViewById(R.id.descTV);




}

public void setImage(Context applicationContext, String imageuri) {

    adimg=(ImageView)itemView.findViewById(R.id.ad_image);

    // We Need TO pass Context

    Picasso.with(applicationContext).load(imageuri).into(adimg);



}

1 个答案:

答案 0 :(得分:1)

如果您确定代码没有错误,我想提醒您Firebase连接是异步的。 所以函数retrieve()第一次返回arrayList的值实际上是空的。 您可以做的是在adapter.notifyDataSetChanged()方法中的for循环后调用onDataChange()