1

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) {

        }
    });

}

Dan Arrick
  • 85
  • 8
  • Data is loaded from Firebase asynchronously. Any code that needs the data, should be inside the `onDataChange` that fires when the data is loaded, or be called from there. See https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Apr 16 '19 at 03:36
  • thanks makes sense! – Dan Arrick Apr 16 '19 at 09:02

0 Answers0