0

I am trying to get number of children.


public int get_number_of_children_place() {
    myRef.addListenerForSingleValueEvent(new ValueEventListener(){
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if(dataSnapshot.exists())
                    lastRow=(int) dataSnapshot.getChildrenCount();
            }

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

            }
        });

        myRef.child("0").child("name").setValue("3f");
        return lastRow;
{

lastRow and myRef is defined as global. the problem is this code do not work if called from onCreate method... it works perfectly when called on click event. The question is how to make it work on oncreate method... thankyou


public class addPlaces extends AppCompatActivity {
    int lastRow=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_places);
        myRef = FirebaseDatabase.getInstance().getReference().child("place");
        int rowNo=get_number_of_children_place();// this says rowNo = 0
   }

   public void on_press(View view){
       int rowNo=get_number_of_children_place();// this says rowNo = 5(number of children)
   }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Data is loaded from Firbase asynchronously. While the data is being loaded, your main code continues. Then when the data is available, your `onDataChange` is called. In your case when `return lastRow` runs, the `lastRow=(int) dataSnapshot.getChildrenCount()` hasn't been called yet. For this reason, all code that needs the data needs be be inside `onDataChange` or be called from there. See https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Feb 17 '20 at 22:52
  • can i use Thread.sleep(2000) and wait in oncreate method? – Shreyanshu Malviya Feb 17 '20 at 22:56
  • Sleeping on the main thread is a bad idea. Your app will appear to be locked up. – Doug Stevenson Feb 17 '20 at 23:02
  • While that may sometimes work, it's a bad idea as the delay is completely arbitrary. Sometimes it may be too short, most often it will be way too long. The approaches in my answer to the linked question are far better, and not that much more difficult once you get the hang of them. – Frank van Puffelen Feb 17 '20 at 23:02

0 Answers0