首页 > 解决方案 > 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

标签: javaandroidfirebasefirebase-realtime-database

解决方案


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


推荐阅读