0

In my code i made

ArrayList<String> allpromo =new ArrayList<>();

as global variable and in onCreate(){}

i wrote

database.getReference().child("PromoCodes").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                allpromo.clear();
                for(DataSnapshot snapshot1 : snapshot.getChildren())
                {
                    String val=snapshot1.child("Promo").getValue(String.class);
                    Toast.makeText(getApplicationContext(), val, Toast.LENGTH_SHORT).show();
                    allpromo.add(val);
                }

            }

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

            }
        });


if(allpromo.isEmpty()) {
          Toast.makeText(getApplicationContext(), "0", Toast.LENGTH_SHORT).show();
      }

It is displaying me all contents of "Promo" from firebase but why it is not able to add items in arraylist. Beacause it Toast "0" .It means mine arraylist is remain empty.And still it Toast items of firebase

But why?enter image description here

and my database is

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • What is getting toasted first? "0" or the values? – Sujal Kumar Feb 26 '22 at 13:32
  • 1
    Loading data from Firebase requires it to make a call over the internet. Like many cloud-based APIs/SDKs, Firebase implements this as an asynchronous operation so that your user can continue to use the app while the data is being retrieved. Then when the data is available, your `onDataChange` is called with that data. But by that time, your toast has long since shown the empty `allpromo`. The solution for this is always the same: all code that needs the data from the database, has to be inside `onDataChange`, be called from there, or otherwise synchronized. – Frank van Puffelen Feb 26 '22 at 15:29
  • @FrankvanPuffelen tx Frank van puffelen..Tx alot – beginner developer Feb 26 '22 at 15:45

1 Answers1

0
database.getReference().child("PromoCodes").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                allpromo.clear();
                for(DataSnapshot snapshot1 : snapshot.getChildren())
                {
                    String val=snapshot1.child("Promo").getValue(String.class);
                    Toast.makeText(getApplicationContext(), val, Toast.LENGTH_SHORT).show();
                    allpromo.add(val);
                }
         if(allpromo.isEmpty()) {
          Toast.makeText(getApplicationContext(), "0", 
                 Toast.LENGTH_SHORT).show();
      }

            }

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

            }
        });




Adnan Bashir
  • 645
  • 4
  • 8