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.
- ValueEventListener responseListener = new ValueEventListener() {
- @Override
- public void onDataChange(DataSnapshot dataSnapshot) {
- if (dataSnapshot.exists()) {
- // Do stuff
- } else {
- // Do stuff
- }
- }
- @Override
- public void onCancelled(DatabaseError databaseError) {
- }
- };
- FirebaseUtil.getResponsesRef().child(postKey).addValueEventListener(responseListener);
Then add the listener to the correct reference in the database. Above, I am adding it to:
- public static DatabaseReference getBaseRef() {
- return FirebaseDatabase.getInstance().getReference();
- }
- public static DatabaseReference getResponsesRef() {
- return getBaseRef().child("responses");
- }