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". 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: