I am trying to add data (The String name) to the list in the nested onDataChange. In the outer onDataChange, the data is being added to the timeIntervals arraylist. In the neste
Welcome to asynchronous data loading, which always messages you up. Contrary to what you think, the data is getting added to timeIntervals
. It's just being added after you print it.
The easiest way to see this is by adding some well placed log statements:
Log.d("timeintervals", "Before starting load additional data");
for (int j = 0; j < apptindex.size(); j++) {
int index = apptindex.get(j);
long apptnum = apptnumber.get(j);
String appnumString = Long.toString(apptnum);
if (daySchedule != null) {
mApptDatabase = FirebaseDatabase.getInstance().getReference().child("Appointments").child(appnumString);
mApptDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("timeintervals": "Additional data loaded");
String name = dataSnapshot.child("targetName").getValue().toString();
timeIntervals.add(name);
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
}
}
Log.d("timeintervals", "After starting load additional data");
When you run this code the output is:
Before starting load additional data
After starting load additional data
Additional data loaded
Additional data loaded
...
This is probably not the order you expected. But it explains perfectly why timeIntervals
doesn't show the additional information when you print it: the data hasn't been loaded yet.
This is because Firebase loads data from the database asynchronously and doesn't block your app while it's loading the data.
The typical solution for dealing with asynchronous data is to move the code that needs the data into the onDataChange
that fires when the data has loaded. E.g. if you move the logging of the timeIntervals
into onDataChange
it will log the intervals each time it loads one of the names.
To learn a lot more about this, I recommend reading these: