Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...