'This program need to verify if somthing exist in my firebase database

My problem is that i need to click twice on my button to execute the ValueEventListener. The first time it goes to another activity without the verification and to work i need to press the return button in emulator and then press again on the search button(intent button).

search.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        databaseReference.child("calendar").child("adrian").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.hasChild(month1.toLowerCase(Locale.ROOT))) {

                    for (int i = Integer.parseInt(date1); i <= Integer.parseInt(date2); i++) {

                        if (snapshot.child(month1.toLowerCase(Locale.ROOT)).hasChild(String.valueOf(i))) {
                            x++;
                        }
                    }
                }
            }

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

        Intent intent = new Intent(MainActivity.this,Image.class);
        intent.putExtra("x",String.valueOf(x));
        startActivity(intent);
    }
});
 


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source