How can I check if a value exists already in a Firebase data class Android

dataSnapshot.child(busNum).getValue() != null

should work.


Rather than getting whole iterable list of data, you can query for exact entry.

  postRef = FirebaseDatabase.getInstance().getReference().child("BusNumber");

    postRef.orderByChild("busNum").equalTo(busNum)
        .addListenerForSingleValueEvent(new ValueEventListener() {

           @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if(dataSnapshot.exists()){
                   //bus number exists in Database
            } else {
                //bus number doesn't exists.
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });

Your approach is wrong.

When you are doing this dataSnapshot.child(busNum).exists(), it's looking for the busNum in the key section, where your keys are -kasajdh....

So instead what you can do is, get the iterable, now when you look for data.child(busNum).exists() it relates to the value

   postRef.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot data: dataSnapshot.getChildren()){
                    if (data.child(busNum).exists()) {
                        //do ur stuff
                    } else {
                       //do something if not exists
                    }
                  }
                }

                @Override
                public void onCancelled(FirebaseError firebaseError) {

                }
            });