1

Retrieving data works but I can't save the retrieved data into an ArrayList. Right after the "onDataChanged()" method ArrayList "profile" seems to have 2 values, but on the return statement it has 0.

static List<Profile> profiles = new ArrayList<Profile>();
static DatabaseReference dbr;

public static List<Profile> loadProfiles(Context context){

    dbr = FirebaseDatabase.getInstance().getReference().child("users").child("hiring");
    dbr.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            //String value = dataSnapshot.getValue(String.class);
            //Log.d("hello", "Value is: " + value);
            List<Profile> profiles2 = new ArrayList<>();

                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Profile profile = snapshot.getValue(Profile.class);
                    //Log.d("hello", profile.getCompanyName());
                    profiles2.add(profile);

                }

                profiles = profiles2;
                dbr.removeEventListener(this);
        }




        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w("hello", "Failed to read value.", error.toException());
        }
    });

    return profiles;

}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Fake
  • 29
  • 1
  • 7

1 Answers1

3

You cannot return something now that hasn't been loaded yet. In other words, you cannot simply return the profiles list outside the onDataChange() method because it will always be empty due to the asynchronous behavior of this method. This means that by the time you are trying to return that result outside that method, the data hasn't finished loading yet from the database and that's why is not accessible.

A quick solution for this problem would be to use the profiles list only inside the onDataChange() method, otherwise I recommend you see the last part of my answer from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Edit: Feb 26th, 2021

For more info, you can check the following article:

And the following video:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Yes, I solved the issue by doing everything I needed to with the data inside "onDataChange()" thank you. – Fake May 31 '18 at 02:48