Home > Net >  This program need to verify if somthing exist in my firebase database
This program need to verify if somthing exist in my firebase database

Time:03-08

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);
    }
});
 

CodePudding user response:

The problem is that calls to Firebase (and most cloud APIs) are asynchronous, and they allow your main code to continue while loading the data in the background. Then once the data is available, your onDataChange is called.

In practice this means that your intent.putExtra("x",String.valueOf(x)); runs well before x ever gets called, something you can most easily verify by running the in a debugger, or placing some log statements.

The solution for this is that all code that needs the data from the database must be inside onDataChange, be called from there, or be otherwise synchronized. So the simplest fix:

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  ;
                }
            }
            //            
  • Related