I am trying to delete a node from my Firebase real-time database using a transaction. I am using a transaction in order to make the user aware if he/she was the one deleting it, or if someone else deleted it just before they could.
This code doesn't work! (P is always null) unless I call the transaction method twice consecutively, then it is not null in the second call. Why?
mBookedSlotsNodeReference.child(booking.getUserUid())
.child(String.valueOf(booking.getStartTime())).runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
BookedSlot p = mutableData.getValue(BookedSlot.class); // Checked in debug mode, and the value is null!
if (p != null) {
//Delete BookedSlot
mutableData.setValue(null);
return Transaction.success(mutableData);
} else {
Log.e("Error","Node doesn't exist");
return Transaction.abort();
}
@Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
if (databaseError == null) {
if (dataSnapshot.getValue() == null) {
Log.e("Success","node deleted!");
} else {
Log.e("fail","something wierd happened!");
}
} else {
Log.e("db error", databaseError.getDetails());
}
}
});
If I query for the node, it is present! But, why is it not found using the transaction?
mBookedSlotsNodeReference.child(booking.getUserUid())
.child(String.valueOf(booking.getStartTime())).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
dataSnapshot.getValue();// Checked in debug mode, and the value is correct!
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Firebase DB structure:
Root{
BookedSlots{
UserUID{
UnixTimeStamp:
classRoom:
UnixTimeStamp:
UserUID:
}
}
}
BookedSlot pojo:
public class BookedSlot {
private long UnixTimeStamp;
private String classRoom;
private String UserUID;
public BookedSlot() {
}
//getters + setters
I am testing the sample app alone, so there is no chance of any entries getting written just after i delete one, or any kind of concurrent entries.
Am I doing something wrong here?
N.B: If I call the transaction method twice, the mutableData is not Null in the second call!!! So, it works correctly!
Am I doing something wrong here?