检查Firebase Android中是否存在ID

时间:2016-04-25 10:48:16

标签: java android database firebase

我正在编写一个Android应用程序,我想检查是否存在密钥以避免重复值。我一直在调查,但看起来我可以添加的只是听众,当我只是想检查一个ID是否存在时。

SO question为例,我想知道-JlvccKbEAyoLL9dc9_v是否存在。我怎么能这样做?

提前致谢。

3 个答案:

答案 0 :(得分:13)

这种方法总是类似于我在这个关于JavaScript的答案中写的:Test if a data exist in Firebase

JButton btnCommunicationType = new JButton("AlwaysOn");
    btnCommunicationType.setFocusPainted(false);
    btnCommunicationType.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(btnCommunicationType.getText().equals("AlwaysOn"))
            {
                btnCommunicationType.setText("REST");
                //TODO:  Insert Code for Switching Communication to REST here
            }
            else if(btnCommunicationType.getText().equals("REST")){
                btnCommunicationType.setText("AlwaysOn");
                //TODO: Insert Code for Switching Communication to AlwaysOne here
            }
        }
    });
    btnCommunicationType.setBounds(275, 199, 97, 25);
    thingWorxConnectionPanel.add(btnCommunicationType);

但请记住,存在Firebase中的推送ID以防止必须执行此类检查。当多个客户端生成推送ID时,它们在统计上保证是唯一的。因此,他们中的任何一个都无法创建与另一个相同的密钥。

任何需要检查项目是否已存在的情况都可能存在竞争条件:如果两个客户几乎同时执行此检查,则它们都不会找到值。

答案 1 :(得分:1)

RxJava 2:

public static Observable<Boolean> observeExistsSingle(final DatabaseReference ref) {
    return Observable.create(emitter ->
            ref.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    emitter.onNext(dataSnapshot.exists());
                    emitter.onComplete();
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    emitter.onError(databaseError.toException());
                }
            }));
}

用法:

public Observable<Boolean> isYourObjectExists(String uid) {
    return observeExistsSingle(databaseReference.child(uid));
}

在你班上:

yourRepo.isYourObjectExists("-JlvccKbEAyoLL9dc9_v")
                .subscribe(isExists -> {}, Throwable::printStackTrace);

答案 2 :(得分:0)

根据@Frank van Puffelen的回答,在使用它之前,有几行可以查看ref - 本身 - 。< / p>

public void saveIfRefIsAbsent(DatabaseReference firebaseRef) {

    DatabaseReference parentRef = firebaseRef.getParent();
    String refString = firebaseRef.toString();
    int lastSlashIndex = refString.lastIndexOf('/');
    String refKey = refString.substring(lastSlashIndex + 1);

    parentRef.child(refKey).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            if (snapshot.exists()) {
                // TODO: handle the case where the data already exists
            }
            else {
                // TODO: handle the case where the data does not yet exist
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) { }    
    });
}

在我的情况下,我有一个Util以编程方式创建架构。我使用它来添加新数据而不覆盖现有数据。