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 right code to do so.
ref = new Firebase(Config.FIREBASE_URL);
postRef = ref.child("BusNumber");
busNum = edtBus.getText().toString().trim();
route1 = route.trim();
seat = edtSeat.getText().toString().trim();
if (!busNum.isEmpty() && !route1.isEmpty() && !seat.isEmpty()) {
postRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(busNum).exists()) {
edtBus.setError("Bus number already exists.");
edtBus.setText("");
} else {
busNumber = new BusNumber();
busNumber.setBusNum(busNum);
busNumber.setRoute(route1);
busNumber.setNumSeat(seat);
postRef.push().setValue(busNumber);
edtBus.setText("");
edtSeat.setText("");
Toast.makeText(AddBusActivity.this, "Saving successful!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(AddBusActivity.this, "Error", Toast.LENGTH_SHORT).show();
Toast.makeText(AddBusActivity.this, firebaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(AddBusActivity.this, "Please complete the information", Toast.LENGTH_SHORT).show();
}
Can somebody help me with this matter? Thanks in advance.
Whether the if statement is correct or not, also my problem is why does the postRef.addListenerForSingleValueEvent
...doesn't work? I tried to test some toast message but the message won't pop out.
Calling the getKey() method on this reference will return the auto-generated key which may then be used to store a corresponding value. The following code, for example, uses the push() method to add a new child at the path stored within the database reference instance: DatabaseReference newChildRef = dbRef.push();
If there is no data, the snapshot will return false when you call exists() and null when you call getValue() on it.
After creating a new project, navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot. Inside that column Navigate to Firebase Realtime Database.
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) {
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With