0

Structure of firebase database

I want to check if a particular device exists in the firebase database before adding it. I have tried using valueevent listener and singlevalue event listener but both were prone to race conditions.

So I tried using Firebase transaction, but even that doesn't work.

Here is the code:

Devices devices=new Devices(devicename,timein,email,timeout);


myRef.child("Device-1").runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        if (mutableData.getValue() != devicename) {
            myRef.child("Device-1").push().setValue(devices);
            // Data does not exist, add it

            return Transaction.success(mutableData);
        }
        return Transaction.abort();
    }

    @Override
    public void onComplete(DatabaseError error, boolean committed, DataSnapshot snapshot) {
        if (error != null) {
            // Handle error
        }
    }
});

I was expecting it to not add the data the second time, as there was always already an entry in the database with the same devicename

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
laos
  • 1

0 Answers0