我们有一个传统的ListView与RecyclerView Adapter和Model类接口。当我们登录Firebase时,我们导航到ListView,ListView中没有加载任何内容。然后我们返回登录活动并重复该过程 然后,所有数据都从一个非常简单的DB子节点表列表中加载 我们厌倦了Firebase RecyclerAdapter没有运气我们可能有错误的UI或版本。我们的问题是为什么我们需要两次前往列表视图来加载数据?我们将发布ListView代码没有生成错误我们尝试将代码放在OnStart方法中没有运气
db = FirebaseDatabase.getInstance().getReference();
dbRef = db.child("Table List");
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren())
listArrayList.add(child.getValue(String.class));
sz = listArrayList.size();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
sz = listArrayList.size();
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(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new TableTrackerAdapter(this,listArrayList);
mRecyclerView.setAdapter(mAdapter);
}
if(sz > 0){
tvNoData.setVisibility(View.INVISIBLE);
mRecyclerView = findViewById(R.id.recycleview);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new TableTrackerAdapter(this,listArrayList);
mRecyclerView.setAdapter(mAdapter);
}
答案 0 :(得分:2)
之所以这样,是因为Firebase数据库是异步的,换句话说,在firebase完成加载数据之前,recyclelerview会填充一个空的arraylist,我之前遇到过类似的问题。
只需将依赖于你的arraylist的所有内容移动到firebase datachange中,问题就会像这样修复。
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) {
}
});