java - Problem to add an object from firebase in a List
问题描述
TestActivity.java
public class TestActivity extends AppCompatActivity {
private DatabaseReference fireBaseRef = ConfigurationFirebase.getFirebaseDatabase();
private Button buttonTest;
private Question question;
List<Question> questionsList = new ArrayList();
private String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simulado);
generateQuestions();
buttonTest= findViewById(R.id.buttonTest);
buttonTest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(TestActivity.this, listaQuestion.get(0).getQuestion().toString(), Toast.LENGTH_LONG).show();
}
});
}
public List<Question> generateQuestions() {
DatabaseReference questionRef = fireBaseRef.child("questions");
questionRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
question = dataSnapshot.child("id").child("1").getValue(Question.class);
name = question.getQuestion().toString();
Question objectQuestion = new Question();
objectQuestion.setQuestion(name);
objectQuestion.setOptionA(question.getOptionA());
objectQuestion.setOptionB(question.getOptionB());
objectQuestion.setOptionC(question.getOptionC());
objectQuestion.setOptionD(question.getOptionD());
objectQuestion.setResult(question.getResult());
questionsList.add(objectQuestion);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
return questionsList;
}
}
I keep getting error java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when i try to show a toast using the List, but with the variable name it shows. The class Question only have getters and setters
解决方案
You are getting 0 because you are returning the list before the data is fetched, see that firebase runs this asynchronous and it gets some time in onDataChange() to fetch the data in order to return it. Please read this answer I posted yesterday How do I pass data out of the onDataChange method? is the same issue.
Also please check this answer from Frank van Puffelen getContactsFromFirebase() method return an empty list
推荐阅读
- python - 为编译运行时关键字编写一个正则表达式
- javascript - 使用 AJAX 和 PHP 删除用户记录时面临的问题
- python - 使用 Python 和 Flask 进行音频直播
- javascript - 使用 jQuery 结果渲染多个 div
- excel - Excel日期舍入计算
- c# - 无法从“void”转换为 System.Threading.Tasks.Task
- tensorflow - 自动将类似 Tensorboard 的损失图保存到图像文件中
- c# - C# - System.ArgumentOutOfRangeExceptionSpecified 参数超出有效值范围
- css - 具有未定义宽度的浮动段落
- java - 在方法中使用字符串的值