Check if ID exists in Firebase Android

10,561

Solution 1

The approach will always be similar to what I wrote in this answer about JavaScript: Test if a data exist in Firebase

ref.child("-JlvccKbEAyoLL9dc9_v").addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    if (snapshot.exists()) {
      // TODO: handle the case where the data already exists
    }
    else {
      // TODO: handle the case where the data does not yet exist
    }
  }

  @Override
  public void onCancelled(FirebaseError firebaseError) { }
});

But keep in mind that push ids in Firebase exist to prevent having to do this sort of check. When multiple clients generate push ids, they are statistically guaranteed to be unique. So there's no way one of them can create the same key as another.

Any case where you need to check if an item already exists is likely to have race conditions: if two clients perform this check almost at the same time, neither of them will find a value.

Solution 2

RxJava 2 :

public static Observable<Boolean> observeExistsSingle(final DatabaseReference ref) {
    return Observable.create(emitter ->
            ref.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    emitter.onNext(dataSnapshot.exists());
                    emitter.onComplete();
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    emitter.onError(databaseError.toException());
                }
            }));
}

Usage:

public Observable<Boolean> isYourObjectExists(String uid) {
    return observeExistsSingle(databaseReference.child(uid));
}

In your class:

yourRepo.isYourObjectExists("-JlvccKbEAyoLL9dc9_v")
                .subscribe(isExists -> {}, Throwable::printStackTrace);
Share:
10,561
stack man
Author by

stack man

hello world

Updated on June 09, 2022

Comments

  • stack man
    stack man almost 2 years

    I am writing an android app and I want to check if a key exists in order to avoid duplicate values. I´ve been investigating but it looks that all I can add is listeners, when I just want to check if an ID exists or not already.

    Taking this SO question as an example, I would like to know if -JlvccKbEAyoLL9dc9_v exists. How can I do this?

    Thanks in advance.

  • stack man
    stack man about 8 years
    Many thanks, it worked perfectly, but I am concerned about your advise about race conditions. What do you mean with push ids? Shouldn´t I make this kind of check? Is there other way to avoid duplicated IDs?
  • Frank van Puffelen
    Frank van Puffelen about 8 years
    I expanded my answer, to more clearly cover the cases of push id vs a different key type.
  • Mohamed Ibrahim
    Mohamed Ibrahim almost 7 years
    funny that I've mplemented this method the same way you did
  • MBH
    MBH almost 7 years
    @MohamedIbrahim :) great ya Habibi :)
  • Mohamed Ibrahim
    Mohamed Ibrahim almost 7 years
    that's more funny :)