[英]How to check if unique entry exists in firebase database or not?
Basically, I want to check if a unique key already exists in the firebase database.基本上,我想检查 firebase 数据库中是否已经存在唯一键。
I have tried using this:我试过使用这个:
Query query = myRef.child("Device-1").orderByChild(Objects.requireNonNull(myRef.child("Device-1").getKey())).equalTo(null);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(), "ye", Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
});
But that just doesn't work and I suspect there is another method to do it.但这行不通,我怀疑还有另一种方法可以做到这一点。
To check if a particular node exists in the Realtime Database, then you have to create a reference that points exactly to that node.要检查实时数据库中是否存在特定节点,您必须创建一个精确指向该节点的引用。 So in code, it should look like this:所以在代码中,它应该是这样的:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference devicesRef = db.child("Devices");
DatabaseReference deviceOneRef = devicesRef.child("Device-1");
DatabaseReference keyRef = deviceOneRef.child("-NJLkBkt96yj6gg0EC1n");
keyRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
if(snapshot.exists()) {
Log.d("TAG", "The document exists.");
} else {
Log.d("TAG", "The Document doesn't exist.");
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
If you don't know the key ("-NJLkBkt96yj6gg0EC1n"), then you have to perform a query that uniquely identifies that node, for example the "deviceid".如果您不知道密钥(“-NJLkBkt96yj6gg0EC1n”),则必须执行唯一标识该节点的查询,例如“deviceid”。 In code, that would be:在代码中,这将是:
Query queryByDeviceId = devicesRef
.orderByChild("deviceid")
.equalTo("BEGIN:VCARD VERSION:3.0 N:;DEVICE-8569 END:VCARD");
queryByDeviceId.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
if(ds.exists()) {
Log.d("TAG", "The document exists.");
} else {
Log.d("TAG", "The Document doesn't exist.");
}
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
If you want to update multiple record when you perfrom a query, then please check my answer from the following post:如果您想在执行查询时更新多条记录,请查看我在以下帖子中的回答:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.