java - 使用 while 循环遍历 Firebase 数据库
问题描述
我创建了一个复习问题表,每次用户答错问题时,都会将一个问题添加到此表中。尝试使用此功能时,我会遍历表格以显示每个问题。
像这样:
databaseref = FirebaseDatabase.getInstance().getReference().child("Review Questions").child(userid).child("Pollution");
databaseref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final Iterator<DataSnapshot> questions = dataSnapshot.getChildren().iterator();
while (questions.hasNext()) {
final DataSnapshot question = questions.next();
t1_question.setText(question.child("question").getValue().toString());
b1.setText(question.child("answer1").getValue().toString());
b2.setText(question.child("answer2").getValue().toString());
b3.setText(question.child("answer3").getValue().toString());
b4.setText(question.child("answerCorrect").getValue().toString());
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
incorrect++;
b1.setBackgroundColor(Color.RED);
b4.setBackgroundColor(Color.GREEN);
description.setBackgroundColor(Color.YELLOW);
description.setText(question.child("description").getValue().toString());
}
我有四个按钮,我刚刚展示了一个按钮作为示例。出于某种原因,它显示了复习问题表中的最后一个问题。所以它不会遍历它们,因为最后一个问题没有下一个值。
我还有一个下一个按钮,它应该用来进入下一个问题,写成这样:
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
b2.setBackgroundColor(Color.LTGRAY);
b1.setBackgroundColor(Color.LTGRAY);
b3.setBackgroundColor(Color.LTGRAY);
b4.setBackgroundColor(Color.LTGRAY);
description.setText("");
description.setBackgroundColor(Color.WHITE);
total = total + 1;
UpdateQuestion();
}
}, 1500);
}
});
显示的数据库树及其打印的问题已圈出:
我的代码有问题吗?
我似乎无法理解它为什么会这样,
是否有可能正在阅读其他问题,尽管我看不到这一点,因为没有什么可以暂停 while 循环?如果是这样,我将如何做到这一点
解决方案
您在循环的每次迭代中设置相同按钮的标签:
b1.setText(...)
所以在循环b1
结束时,answer1
以最后一个问题的值结束。
您需要为每个问题拥有/生成 UI 元素(标签、文本视图、按钮)。执行此操作的典型方法是使用RecyclerView
. 我建议阅读有关从 firebase 填充 recyclerview 的内容,因为该主题非常广泛。
推荐阅读
- flush - 同步等待 rsyslog 刷新完成
- java - 清除应用缓存时,Firebase 匿名身份验证是否仍然存在?
- tfs - Teamcity:如何签出根目录,但只能从子目录中查看更改
- socket.io - 如何使用渡槽和套接字获取完整数据?
- xcode - Xcode 10 不在导航窗格中显示文件
- python-3.x - 如何使用python获取正方形的颜色序列?
- php - 查看 [] 未找到
- .net - Dapper:结构的自定义类型处理程序
- shell - SQLPlus 检查ShellScript中是否存在表
- json - 在 Talend 中使用 tExtractJSONFields