[英]Firebase listener in listener skipped
在我的應用程序中,我使用了 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) {
}
});
}
之前用過,因為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) {
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.