0

What I am trying to do is load a list of values (Usernames) from a child directory in Firebase. I have a method createProviderList(int locGrid) that returns the arraylist of user data. Since it is asynchronous however, it executes the return statement before the data is read. How do I overcome this? I apologize for my ignorance as I am fairly new to Android/Java. Can someone please explain how to handle this?

Just to be clear, all of this code does what I need except that the return providerList; is executed before any of the elements of the ArrayList are added.

public static ArrayList<ProviderInfo> createProviderList(int locGrid) {


     ArrayList<ProviderInfo> providerList = new ArrayList<ProviderInfo>();
     ArrayList<String> availableProviders = new ArrayList<String>();
     FirebaseAppUtilsHSquared fbu = new FirebaseAppUtilsHSquared();


    DatabaseReference db = FirebaseDatabase.getInstance().getReference().child(MainActivity.GPS_PATH)
            .child(String.valueOf(locGrid));

    db.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot ds : snapshot.getChildren()){
                providerList.add(fbu.getUserProfileInfo(String.valueOf(ds.getValue())));
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

    return providerList;

These values here

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • https://stackoverflow.com/questions/57330766/why-does-my-function-that-calls-an-api-return-an-empty-or-null-value – a_local_nobody Nov 15 '21 at 19:23
  • What you're seeing is the expected behavior. Like most cloud-based APIs, data is loaded from Firebase asynchronously - and your `onDataChange` gets called (possibly much) later than the `return providerList`. The solution is always the same: any code that needs the data from the database needs to be inside `onDataChange` or be called from there. I linked some previous questions that show how to do this. – Frank van Puffelen Nov 15 '21 at 20:10
  • The reason I was doing it this way was to avoid writing this a bunch of times in my code. I need to call this more than once and was trying to setup a method that can be used elsewhere in the code to avoid rewriting. I went back through and copy/pasted this where I needed it for now. If there is another way to accomplish this that I am missing, I am open. Thank you for the help! – Victor Humphrey Nov 18 '21 at 23:08

0 Answers0