I'm trying to get name data from Firebase using uid from another collection with an interface, set that data into a variable, and do some task. Then let's say I want to show a Toast if the task is done or not.
This is the method
public void createExcel(final String grade) {
Boolean taskSuccess;
DatabaseReference attendanceRef = FirebaseDatabase.getInstance().getReference().child("attendance").child(grade);
attendanceRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
String thisUid;
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot ds2 : ds.getChildren()) {
thisUid = ds2.child("uid").getValue().toString();
readData(thisUid, new MyCallBack() {
@Override
public void onCallback(String value) {
thisName[0] = value;
//Do some task
if (//task success) {
taskSuccess == true;
}
}
});
}
}
System.out.println(taskSuccess); //taskSuccess value is always false
}
});
}
This is my interface
public interface MyCallBack {
void onCallback (String value);
}
This is my readData method
public void readData (String uid, final MyCallBack myCallBack) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(uid);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
String value = snapshot.child("name").getValue().toString();
myCallBack.onCallback(value);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
Is there any way I can set that taskSuccess value inside onDataChange method and use it outside onDataChange method? Because if I make a Toast inside readData
it will make some Toasts because of the loop to get the data from database