1

I want to fetch data from inside Firebase to check whether this user exists in database but there's a problem that i can't solve , listener trigger late this is my code :-

  • if I remove while loop i can't fetch object fast
  • if I keep while loop i enter infinite loop , i don't know why why listener don't trigger

    DataSnapshot fetched ;
    public boolean user_exist(final String user) throws Exception {
    users.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            fetched = dataSnapshot ;
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    while (fetched == null){
        Log.e("dbController","not fetched yet");
    }
    return fetched.hasChild(user);
    }
    
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Lawyer App
  • 11
  • 3
  • You don't show how you are triggering the event. Is there any chance the while loop blocks the thread? You need to trigger the event from another thread. And don't use a while that is running at 100%. Your listener could add to a queue instead, and you can log when an item is added to the queue. – Just another Java programmer Sep 25 '17 at 18:50
  • Data is loaded from Firebase asynchronously. You cannot return it from a (regular, synchronous) function. See https://stackoverflow.com/questions/33203379/setting-singleton-property-value-in-firebase-listener – Frank van Puffelen Sep 25 '17 at 18:55
  • so you suggest to make main thread wait for time enough that listener trigger ? i already tried this solution but didn't workout first time i call function fetched is null second time it is not null – Lawyer App Sep 25 '17 at 18:58
  • Frank van Puffelen yeah i think this is my problem , thanks – Lawyer App Sep 25 '17 at 18:59

1 Answers1

0

Firebase has to fetch the data from database and bring it in your app. This may take time, hence it should be done in background. When you add valueEventListener, the fetching is done in background. You may display a progressBar to show data is still loading, and once data is in hands, do the rest of code:

users.child(user).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            funUserExists();
        } else {
            funNoUser();
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
    }
});
npk
  • 1,512
  • 1
  • 13
  • 26