qqrrrr
qqrrrr

Reputation: 585

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

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

Upvotes: 13

Views: 53914

Answers (5)

if(!(dataSnapshot.child("Users").child(busNum).exists()))

and then hashmap object

Upvotes: 1

silverFoxA
silverFoxA

Reputation: 4659

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

                }
            });

Upvotes: 20

Vishal Sharma
Vishal Sharma

Reputation: 341

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

            }
        });

Upvotes: 16

Bob Snyder
Bob Snyder

Reputation: 38299

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)

Upvotes: 1

Abhi V
Abhi V

Reputation: 724

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

should work.

Upvotes: 4

Related Questions