I want to check if the bus number already exists in the database of Firebase.
Here\'s my sample code. I\'ve been searching for the past days but I can\'t find the rig
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) {
}
});
dataSnapshot.child(busNum).getValue() != null
should work.
if(!(dataSnapshot.child("Users").child(busNum).exists()))
and then hashmap object
It is difficult to guess the problem because you do not show how busNum and busNumber are defined and managed. Is busNumber a String?
push() creates a reference to an auto-generated child location. The auto-generated key looks something like -KPB_cS74yoDaKkM9CNB.
The statement postRef.push().setValue(busNumber) stores value busNumber in location BusNumber/<push-generated-key>.
The statement dataSnapshot.child(busNum).exists() tests for the existence of a value at location BusNumber/<busNum>. It will not be true unless busNum is one of the keys created by push().
It's not clear how you want your data structured. If your bus numbers are Strings and are unique, you do not need to generate a key with push(). You could store the existence of bus numbers using:
postRef.child(busNumber).setValue(true)
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) {
}
});