在我的应用程序中,我使用了firebase数据库。有问题和相应的评论存储在单独的节点中。现在,我尝试使用一个监听器获取问题,并使用第二个监听器访问评论。不幸的是,我被他们的行为搞糊涂了:recyclerView总是得到一个空的questionsList,就像第二个侦听器被跳过一样。但是,在recyclerView获得列表并设置了适配器之后,我的LogCat开始打印问题和评论信息。但是,为什么在处理数据的for循环结束之前就填充和使用recyclerView呢?
获取信息的方法:
private void getQuestionsFromDatabase() {
mQuestions.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
questionList = new ArrayList<>();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
final String title = dataSnapshot1.child("title").getValue().toString();
final String question = dataSnapshot1.child("question").getValue().toString();
final String commentId = dataSnapshot1.child("commentId").getValue().toString();
mComments.child(commentId).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
count = dataSnapshot.getChildrenCount();
QuestionModel questionModel = new QuestionModel(title, question, commentId, String.valueOf(count));
questionList.add(questionModel);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
Log.d("questionList length: ", String.valueOf(questionList.size()));
recyclerViewAdapter = new RecyclerViewQuestionAdapter(questionList, getActivity());
recyclerViewlayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
recyclerView.setAdapter(recyclerViewAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}发布于 2019-04-20 16:51:14
之前使用过它,因为onDataChange是异步的,这意味着编译器不会等到从数据库获取数据后才执行代码,而是在侦听器之后执行代码。因此,要解决您的问题,您应该执行以下操作:
mComments.child(commentId).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
count = dataSnapshot.getChildrenCount();
QuestionModel questionModel = new QuestionModel(title, question, commentId, String.valueOf(count));
questionList.add(questionModel);
Log.d("questionList length: ", String.valueOf(questionList.size()));
recyclerViewAdapter = new RecyclerViewQuestionAdapter(questionList, getActivity());
recyclerViewlayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
recyclerView.setAdapter(recyclerViewAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}https://stackoverflow.com/questions/55771832
复制相似问题