0

Every time I run this code the for loop stops after some random number of iterations, but not 100. If I comment out the data retrieving part from firebase, the for loop runs fully.Can I know the reason why the loop stops in between?

firstslot = new ArrayList<>();

for (i =1; i<=100; i++)
{

               final String string = String.valueOf(i);

               reference.child(string)
                       .addValueEventListener(new ValueEventListener() {
                           @Override
                           public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                               if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")) && (dataSnapshot.hasChild("age"))) {
                                   String check = "BOOKED";
                                   item = new book(string, deptid, date, check, Color.CYAN);
                                   firstslot.add(item);
                               } else {

                                   String check = "";
                                   item = new book(string, deptid, date, check, Color.TRANSPARENT);
                                   firstslot.add(item);
                               }
                           }

                           @Override
                           public void onCancelled(@NonNull DatabaseError databaseError) {

                           }
                       });

           }

       RecyclerView myrv = findViewById(R.id.booksrecyclerview);
       bookadapter myadapter = new bookadapter(this, firstslot);
       myrv.setLayoutManager(new GridLayoutManager(this, 5));
       myrv.setAdapter(myadapter);
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
mayookh
  • 9
  • 2
  • 1
    Data is loaded from Firebase asynchronously. By the time your `new bookadapter(this, firstslot)` runs, the code in `onDataChange` hasn't run yet. You can check this by running the code in a debugger, and putting breakpoints on both lines. You'll see they run in a different order from what you expected. For that reason, any code that uses the data from the database must be inside `onDataChange` or be called from there. See my longer answer and sample here: https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Aug 22 '19 at 13:25

1 Answers1

1

Mixing up synchronous and asynchronous execution causes this - unless understanding this fundamental condition, you might struggle with it. Use callbacks to indicate, whenever a query had completed... a synchronous for loop just won't cut it, because it will create a race condition.

Think of it, as it were a 100 AsyncTask.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216