0

Basically, I want to check if a unique key already exists in the firebase database.

enter image description here

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
laos
  • 1

1 Answers1

0

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:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193