gpt4 book ai didi

java - 监听器中的 Firebase 监听器已跳过

转载 作者:行者123 更新时间:2023-11-30 10:04:42 27 4
gpt4 key购买 nike

在我的应用程序中,我使用了 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) {

}
});

}

关于java - 监听器中的 Firebase 监听器已跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55771832/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com