RecyclerView在首次启动时不会从Firebase加载数据

时间:2017-10-25 07:27:18

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

我从Firebase获取数据,但RecyclerView未在首次启动时显示该数据。它会在我再次打开活动时显示数据。

在我的主要活动中 -

databaseReference = FirebaseDatabase.getInstance().getReference("data").child("childdata");
    recyclerView = (RecyclerView)findViewById(R.id.recyclerviews);
    recyclerView.setHasFixedSize(true);
    recyclerAdapter = new DisplayRecyclerAdapter(list,this);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(recyclerAdapter );
    recyclerAdapter.notifyDataSetChanged();
    loadRecyclerData();
}

private void loadRecyclerData() {
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                String da = postSnapshot.getValue().toString();
                list.add(da);
        }
    });
}

1 个答案:

答案 0 :(得分:4)

通知onDataChange内的适配器导致您的列表在那里更新

databaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot postSnapshot:dataSnapshot.getChildren()) {
            String da = postSnapshot.getValue().toString();
            list.add(da);
        }
        recyclerAdapter.notifyDataSetChanged(); 
    }
)};