原因是因为firebase数据库是异步的,换句话说,在firebase加载完数据之前,recyclerview将被一个空的arraylist填充,我以前遇到过类似的问题。
只需在FireBase DataChange中移动依赖于ArrayList的所有内容,问题就会像这样解决。
public void setupRecyclerView(){
if(sz == 0){
tvNoData.setVisibility(View.VISIBLE);
tvNoData.setText("No Quiz's Found\n\nClick On Make New Quiz");
mRecyclerView = findViewById(R.id.recycleview);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new TableTrackerAdapter(MainActivity.this,listArrayList);
mRecyclerView.setAdapter(mAdapter);
}
if(sz > 0){
tvNoData.setVisibility(View.INVISIBLE);
mRecyclerView = findViewById(R.id.recycleview);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new TableTrackerAdapter(MainActivity.this,listArrayList);
mRecyclerView.setAdapter(mAdapter);
}
}
db = FirebaseDatabase.getInstance().getReference();
dbRef = db.child("Table List");
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot != null){
for (DataSnapshot child : dataSnapshot.getChildren()){
listArrayList.add(child.getValue(String.class));
}
sz = listArrayList.size();
setupRecyclerView();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});