我已经创建了一个复习问题表,每当用户输入错误的问题时,一个问题就会添加到该表中。尝试使用此功能时,我会遍历表格以显示每个问题。
像这样:
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
。我建议您阅读populating recyclerview from firebase,因为该主题非常广泛。
您几乎自己回答了这个问题。问题是您在while循环中为按钮设置了OnClickListener,而没有等待问题被回答。每个按钮可以有1个OnClickListener,即使尚未回答问题,每次循环迭代都将覆盖此值。您会注意到,当您在循环内的任何行上设置调试标记,然后运行调试时。
在这种情况下,我不会使用while循环,而是引入一个计数器/索引变量,例如intquestionIndex,并在每次回答问题时增加该计数器。可以根据该索引显示下一个问题,获胜条件将是(index == questions.length -1)或类似的值。