0

I am using firebase ListenerForSingleValueEvent and trying to get a list of Address class and put them into an arraylist but this thing is not working.. i tried to call a function or something but it didnt work

mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {



            for (DataSnapshot postSnapshot: dataSnapshot.child("addresses").getChildren()) {

               Adress adress = new Adress(postSnapshot.getValue(Adress.class));
                adresses.add(adress);

            }

        }

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

        }
    });

I have no idea how to solve it and i didnt find anyone has the same problem as me

Please help,Thanks

edit1: the problem is i cant add the address class to the arraylist using anything

it's just like i cant do it inside the listener, i checked that everything is ok .. also when i check the adresses arraylist size inside the lister it increases then out of the listener it returns to 0.. like the adresses.add function worked only at the listener itself or something like that

Mohad12211
  • 353
  • 3
  • 9
  • What doesn't work when you run this code? In other words: when you run this code, what did it do? And what did you expect it to do? I also highly recommend running the code in a debugger and setting breakpoints on each line, as Stack Overflow is a highly inefficient interactive debugger. – Frank van Puffelen Apr 21 '19 at 14:38
  • @FrankvanPuffelen i updated the question – Mohad12211 Apr 21 '19 at 14:52
  • "the problem is i cant add the address class to the arraylist using anything" The code you shared doesn't show this problem, which makes it hard for us to help. I'll explain below what the problem is based on your update. – Frank van Puffelen Apr 21 '19 at 15:08
  • You're dealing with a typical problem that many developer new to Firebase (and cloud APIs in general) have. Data is loaded from Firebase asynchronously. As the data is being loaded, your main code continues to run. Then when the data is available, your `onDataChange` gets called. Most likely you're trying to access the array in the main code, when it hasn't been updated yet. Any code that needs the data from the database needs to either be inside `onDataChange` or be called from there. See my answer here: https://stackoverflow.com/a/50435519/209103 – Frank van Puffelen Apr 21 '19 at 15:09

0 Answers0