简体   繁体   English

如何检查 Firebase 数据类 Android 中是否已存在值

[英]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.我想检查一下 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? if 语句是否正确,我的问题也是为什么postRef.addListenerForSingleValueEvent ...不起作用? I tried to test some toast message but the message won't pop out.我试图测试一些吐司消息,但消息不会弹出。

这是我的 firebase 数据库

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... .当你在做这个dataSnapshot.child(busNum).exists() ,它busNum在 key 部分寻找busNum ,你的键是-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因此,您可以做的是获取iterable ,现在当您查找data.child(busNum).exists()它与值相关

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

                }
            });

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

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

应该工作。

It is difficult to guess the problem because you do not show how busNum and busNumber are defined and managed.很难猜测问题所在,因为您没有展示busNumbusNumber是如何定义和管理的。 Is busNumber a String? busNumber是字符串吗?

push() creates a reference to an auto-generated child location. push()创建对自动生成的子位置的引用。 The auto-generated key looks something like -KPB_cS74yoDaKkM9CNB .自动生成的密钥类似于-KPB_cS74yoDaKkM9CNB

The statement postRef.push().setValue(busNumber) stores value busNumber in location BusNumber/<push-generated-key> .语句postRef.push().setValue(busNumber)将值busNumber存储在位置BusNumber/<push-generated-key>

The statement dataSnapshot.child(busNum).exists() tests for the existence of a value at location BusNumber/<busNum> .语句dataSnapshot.child(busNum).exists()测试在位置BusNumber/<busNum>处是否存在值。 It will not be true unless busNum is one of the keys created by push() .除非busNumpush()创建的键之一,否则它不会为真。

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() .如果您的总线编号是字符串并且是唯一的,则不需要使用push()生成密钥。 You could store the existence of bus numbers using:您可以使用以下方法存储巴士号码的存在:

postRef.child(busNumber).setValue(true)

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

然后是 hashmap 对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM