I'm having trouble getting a String value from within a Firebase database dataSnapshot in a dataSnapshot. I would like to loop through keys from the "Table" dataSnapshot and then use each key to print a value in another dataSnapshot. The value I print from the inner snapshot is correct but it is not available to the external snapshot and variable I want to assign it to. Is there a more correct way to do this? Here is a sample of what I'm trying:
String extracted;
String key;
onCreate(){
DatabaseReference dbRef1 = FirebaseDatabase.getInstance().getReference().child("Table");
dbRef1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()){
key = data.getKey();
DatabaseReference dbRef2 = FirebaseDatabase.getInstance().getReference().child(key);
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
extracted = dataSnapshot.getValue().toString();
System.out.println(extracted);//prints correct value
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
System.out.println(extracted); //prints null
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}