0

I'm trying find out if a Firebase key exists using Firebase Android Api. Here is the code snippet:

  Firebase ref = new Firebase("https://[MYFB].firebaseio.com/");
  ref.addChildEventListener(new ChildEventListener() {
      @Override
      public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        if (dataSnapshot.exists()){
          dataSnapshot.getKey();
        }
      }
      //...
      @Override
      public void onCancelled(FirebaseError err) {
      }
    });

The problem with this approach is that I can't get a 'DataSnapshot' without resorting to asynchronous callback 'ChildEventListener()'. Since the call is asynchronous, my code does not know if the key doesn't exist or the onChildAdded() has not been consumed yet.
When searching for a solution I found the method '.once()' in JS Api that would solve the problem, but there is no 'synchronous' equivalent in the Android Api.

Am I missing something obvious?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
seanpj
  • 6,735
  • 2
  • 33
  • 54
  • Java has built-in mechanisms to deal with this. See http://stackoverflow.com/questions/33203379/setting-singleton-property-value-in-firebase-listener/33204705#33204705 . But I recommend taking the red pill and accepting the asynchronous nature of this process. – Frank van Puffelen Dec 17 '15 at 21:56
  • @FrankvanPuffelen That's what I'm doing now, but it gets really messy considering that I'm storing values from another async universe - [GDAA](https://developers.google.com/drive/android/intro). Thanks! – seanpj Dec 17 '15 at 22:05
  • The solution is typically to not *store* the value, but to update the UI whenever the value changes. Note btw that `once()` in JavaScript is also asynchronous. Firebase doesn't offer synchronous data access, since that is counter to the logic of monitoring a location for all data changes. – Frank van Puffelen Dec 17 '15 at 23:54

0 Answers0