0

before reading I'm a newbie trying to learn android development so don't go hard on me, please.

I have this Realtime database firebase :

enter image description here

I'm trying to check if the entered email exists , i've tried a method but it did not work out for me.

I tried this method :

private boolean checkIfExistes() {


    reference.child("Users").orderByChild("email").equalTo(Email.getText().toString()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists())
                CheckExists =true;
            else
                CheckExists =false;
        }

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

        }
    });

    if (CheckExists)
        return  true;
    else
        return false;

}

it always returns false though even if the email exists. Help please.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Noor Odah
  • 3
  • 4
  • addListenerForSingleValueEvent is asynchronous and returns immediately. The callback you provide to it doesn't get invoked until some unknown time later, which means that your function always immediately returns false. Try putting log statement inside the onDataChange callback to see what I mean. – Doug Stevenson Jan 17 '19 at 06:27
  • i tried and turned out as you stated ,what would be the solution tho ? – Noor Odah Jan 17 '19 at 06:41
  • The solution is to only use the result in the callback itself, or a functions it calls, passing the result to it. – Doug Stevenson Jan 17 '19 at 06:44
  • Can you help me and write it as code , as that i'm not fully understanding what to do. – Noor Odah Jan 17 '19 at 06:46
  • I think you should go for getting data into Iterable and then compare for the field you want – Deep Patel Jan 17 '19 at 07:29
  • @DeepPatel can you please tell me how to do so , i'm really new and self learning , so it would be really helpful if you wrote me the code to do so. – Noor Odah Jan 17 '19 at 07:35
  • Check **[this](https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method/47853774)** and **[this](https://stackoverflow.com/questions/47893328/checking-if-a-particular-value-exists-in-the-firebase-database/47893879)** out. – Alex Mamo Jan 17 '19 at 09:24

2 Answers2

0
private DatabaseReference rootRef,userRef;

get the initialize firebase in oncreare method

rootRef = FirebaseDatabase.getInstance().getReference();
userRef = rootRef.child("Users");  

here the code for checking email exist or not

userRef.orderByChild("email").equalTo(emailEdt.getText().toString())
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    hideProgress();
                    if (dataSnapshot.exists()){
                        Toast.makeText(LoginActivity.this,"User already exists",Toast.LENGTH_SHORT).show();
                    }else {
                        UserLogin user = new UserLogin(emailEdt.getText().toString(),profilePath);
                        DatabaseReference db = userRef.push();
                        db.setValue(user);
                        //Log.d(TAG,"user key is::: "+db.getKey());
                        prefs.savEmail(emailEdt.getText().toString());
                        prefs.savProfileUrl(profilePath);
                        prefs.savKey(db.getKey());
                        openMainActivity();
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    hideProgress();
                    Toast.makeText(LoginActivity.this,databaseError.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
  • I think this ways goes if i'm using firebase auth , but i'm not , i'm using my own way and already tried the idea of whats written , thanks for your try to help me but this won't work in my case. – Noor Odah Jan 17 '19 at 08:39
0

Try this:

boolean CheckExists =false;   //declare and assign default value in global scope

reference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        Iterable<DataSnapshot> userChildren = dataSnapshot.getChildren();

        for (DataSnapshot user: userChildren) {
            User u = user.getValue(User.class);      //make a model User with necessary fields

            if(u.email.equalsIgnoreCase(Email.getText().toString())){
                CheckExists =true;
            }
        }
    }

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

    }
});
Deep Patel
  • 2,584
  • 2
  • 15
  • 28
  • 1
    This worked for getting it right , but another problem popped up ,CheckExists returns to false after exiting the addListener method idk why – Noor Odah Jan 17 '19 at 09:41
  • check updated answer. I declared and assigned value for boolean in global scope, value will be changed only if matching record gets found. – Deep Patel Jan 17 '19 at 09:44
  • Actually is it seems its because of the asynchronous computation the method finishes its call before even getting the result of the firebase. i've tried a solution Alex Mamo put in another question , but it didn't work ou.. – Noor Odah Jan 17 '19 at 10:29
  • Fixed it by putting the whole code in the method instead of waiting for its callback – Noor Odah Jan 17 '19 at 12:26