0

In this program, I'm setting the value of one array element(flag1[0]) to 1 , if the 'if' condition is satisfied.When I print it(inside the class) , it shows the value set as 1. But when I'm trying to access it outside the inner class it shows value as 0. How should I resolve it ? ( getCount() and setCount() are getters and setters, even they don't work!)

public boolean checkUser(final String user, String program) {

    database = FirebaseDatabase.getInstance();
    final DatabaseReference reference;

    reference = database.getReference("UserNames").child(program);

    final int[] flag1 = {0};
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {


            for (DataSnapshot data : dataSnapshot.getChildren()) {

                String key = data.getKey();
                Log.println(Log.ERROR,"msg",key);

                if (data.getKey().equals(user))
                {
                    musername.setError("UserName already Exists1!");
                    flag1[0] = 1;
                    setCount(1);
                    Log.println(Log.ERROR,"msg", String.valueOf(flag1[0])+String.valueOf(getCount()));//Shows 1 here

                }
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    Log.println(Log.ERROR,"mesg", String.valueOf(flag1[0])+String.valueOf(getCount()));//Shows 0 here
    if(getCount()==0)
        return true;
    return  false;


}
  • All the section in your inner class will be executed when the event is triggered. – Juan Carlos Mendoza Dec 27 '17 at 14:51
  • Yea, but how should I resolve it ? @JuanCarlosMendoza – Atharva Karanje Dec 27 '17 at 14:52
  • Code runs sequentially, while the data is loaded asynchronously. This means that by the time your `return` statement runs, the data hasn't loaded yet. The solution is to either move the code that needs the data **into** `onDataChange()` (as shown [here](https://stackoverflow.com/a/33204705)) or invoke it from there (as shown [here](https://stackoverflow.com/a/40099900)). – Frank van Puffelen Dec 27 '17 at 15:58

1 Answers1

0

Due the asynchronous behaviour of onDataChange() method, you cannot simply use this line of code:

Log.println(Log.ERROR,"mesg", String.valueOf(flag1[0])+String.valueOf(getCount()));

Outside that method, because it will always be null. Here some more information.

To solve this, use that value only inside that method and your problem will be solved. Otherwise, try to understand the async concept and see my answer from this post

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193