QNA > H > How To Check A Child Exist In Firebase Database Using Android

How to check a child exist in firebase database using Android

Firebase makes this nice and easy. Depending on how your database is structured, you could do something like this. An example for a social media style application, where we need to check multiple times if a value exists. If you only need to do it once, you can use a SingleValueEvent listener.

First, instantiate a ValueEventListener and inside the onDataChange method check if the value exists.

  1. ValueEventListener responseListener = new ValueEventListener() { 
  2. @Override  
  3. public void onDataChange(DataSnapshot dataSnapshot) { 
  4. if (dataSnapshot.exists()) { 
  5. // Do stuff  
  6. } else { 
  7. // Do stuff  
  8.  
  9. @Override  
  10. public void onCancelled(DatabaseError databaseError) { 
  11.  
  12. }; 
  13.  
  14. FirebaseUtil.getResponsesRef().child(postKey).addValueEventListener(responseListener); 

Then add the listener to the correct reference in the database. Above, I am adding it to:

  1. public static DatabaseReference getBaseRef() { 
  2. return FirebaseDatabase.getInstance().getReference(); 
  3.  
  4. public static DatabaseReference getResponsesRef() { 
  5. return getBaseRef().child("responses"); 

Di Conrado Davick

Il GPS mobile funziona a bordo degli aerei? :: Chi sono alcuni dei giocatori rappresentati dall'agente Sam Levinson?
Link utili