I have a block of code that gets called before another block of code. I want the first block of code to execute entirely before the other code gets called as it is null otherwise. The code is shown below
public void displayGraph1() {
xnumsList = new ArrayList<>();
namesList = new ArrayList<>();
xxx = new ArrayList<>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("child");
ref.addValueEventListener(new ValueEventListener() {
@Override
public synchronized void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
key = child.getKey();
DatabaseReference checkingWhoisInWhatChild = FirebaseDatabase.getInstance().getReference().child("child").child(key);
checkingWhoisInWhatClass.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String module = dataSnapshot.child("a").getValue().toString();
String xnum = dataSnapshot.child("b").getValue().toString();
for (int i = 0; i < arrayOfModules.size(); i++) {
String lecturerModule = arrayOfModules.get(i);
if (module.equals(lecturerModule)) {
xxx.add(xnum);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
//null array
for (int i = 0; i < xxx.size(); i++) {
Log.d("dddd", "arraycontents" + xxx.get(i));
}
Obviously this is not the whole method but my point is that the loop at the bottom gets called before the preceding code due to asynchronous calls. I want a way to make sure that the code above is executed first so that the size of the array in the loop is not null. I have debugged the code and the array is not empty / null normally so I'm 100% sure that this is an asynchronous call that is causing the issue of the empty array in the loop. I'm looking for a way to synchronize the code, I have tried using the keyword "synchronized" on the functions and I have even tried to make a single thread for the entire function but this hasn't proven to work for me. Any help is appreciated. Thank you