13

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.

here is my firebase database

Jenea Vranceanu
  • 4,530
  • 2
  • 18
  • 34
qqrrrr
  • 575
  • 2
  • 8
  • 22
  • do you have any firebase rules setup preventing you from reading the database? Maybe add a Log in the onCanceled and print out the firebase error if there is one. – Linxy Aug 15 '16 at 07:38
  • @linxy yes I already did. But as far as I can remember. There was no error – qqrrrr Aug 25 '16 at 08:39
  • Have you found the solution? – silverFoxA Jan 14 '17 at 04:19
  • 1
    this because you did not use the calback function and interface i have also the same problem as your that for ( datasnap shot /....) full method did not work it just give whether the null value or null object reference or you did not get the desired value see the link of my question .. and a nice person guide me by giving me the link .. the first one link helped me i use callback and interface trick. [Whey your code firebase database did not work click this hyperlink ](https://stackoverflow.com/questions/51582992/get-all-table-values-from-firebase-null-object-reference-firebase-database) – Sibtain Aug 04 '18 at 19:10

5 Answers5

20

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) {

                }
            });
knoxgon
  • 1,070
  • 2
  • 15
  • 31
silverFoxA
  • 4,549
  • 7
  • 33
  • 73
16

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) {

            }
        });
Vishal Sharma
  • 311
  • 3
  • 7
4
dataSnapshot.child(busNum).getValue() != null

should work.

Abhi V
  • 714
  • 1
  • 4
  • 19
  • but it doesn't work. Even if I try to toast some message inside the onDataChange method, there would never pop out a message. – qqrrrr Aug 15 '16 at 03:46
  • Check your Firebase auth rules maybe? The rules might be preventing you from doing so. – Abhi V Aug 15 '16 at 08:59
  • But I'm not creating a new user. It's stored in the database. Do I still need to check my auth rules? – qqrrrr Aug 17 '16 at 02:28
  • sorry, i meant your database rules, not auth – Abhi V Aug 17 '16 at 05:34
  • Another problem might be that you're using old Firebase so it might be deprecated? – Abhi V Aug 17 '16 at 05:35
  • but this is my database rules `{ "rules": { ".read": "true", ".write": "true" } }` – qqrrrr Aug 23 '16 at 01:13
  • Then my best guess is what I said above. Maybe Firebase might not support the old version any more. – Abhi V Aug 23 '16 at 03:26
  • I see, I tried to update my firebase to the latest version of 9.4.0. But I can't check it yet coz i'm still downloading/updating my SDK google repo – qqrrrr Aug 23 '16 at 09:14
  • hi @Abhi I already put some image of the firebase database structure. I hope that helped. And also, you're right. Firebae does not support the old version. But the thing is ... this code snippet `dataSnapshot.child(busNum).getValue() != null` didn't work. It will save the as new BusNumber data in Firebase – qqrrrr Aug 25 '16 at 06:59
1

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)

Bob Snyder
  • 37,759
  • 6
  • 111
  • 158
  • I don't understand why I need to setValue(true).. All I wanna do is to check if the bus number already exist in the database. cause if the bus number exist it will prompt but if not it will create an new set of bus in the database – qqrrrr Aug 17 '16 at 02:30
  • @tin: Is `busNumber` a String? – Bob Snyder Aug 17 '16 at 02:51
  • http://stackoverflow.com/questions/43752247/how-to-check-already-existed-email-in-firebase-database – chris May 03 '17 at 06:15
1
if(!(dataSnapshot.child("Users").child(busNum).exists()))

and then hashmap object

Mustafa
  • 5,624
  • 3
  • 24
  • 40
  • 2
    While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run. – Mustafa Apr 21 '20 at 15:27