2

I'm currently working on a project and I need to be able to delete from a database I've already created. I created it using the .push() to the database hence a unique key is created and thus needed for delete operations.

I tried using the answer from Frank Van Puffelen here How to delete from firebase realtime database?, but I ran into a bug where if two nodes have the same title they'll be deleted.enter image description here

The image shows how my Firebase database looks:

A bit of assistance or direction to an answer would go a long way. Thanks

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
nelsola
  • 108
  • 9

1 Answers1

1

If you want to delete a single element from your database, you need to know the path to that element, which includes also that pushed key. Your reference should look like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference keyRef = rootRef.child("-KlSNx87aYigsH3lLp0D");
keyRef.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if (task.isSuccessful()) {
            Log.d("TAG", "Element removed successfully!");
        }
    }
});

Otherwise, you can use a query that looks exactly like this:

Query idQuery = rootRef.orderByChild("id").equalTo(1);

In this case, Frank Van Puffelen's answer from the following post:

Will work perfectly fine.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Thank you for your answer Alex Mamo, The first scenario is what i want but i want to know how to get the key because i dont know it as it is randomly generated when i push information into the realtime database. I already tried using the second case, using Frank Van Puffelen's code, but it created a bug where if two items on my list have the same "id" both of them would be deleted. If only i could somehow get the actual key when adding data to the database or when i want to delete data. – nelsola Apr 27 '20 at 10:24
  • If you want to use the first solution, please check **[this](https://stackoverflow.com/questions/51787784/how-to-get-specific-pushedid-in-firebase/51788244)** out and tell me if it works. – Alex Mamo Apr 27 '20 at 10:29
  • 1
    Thanks a lot Alex Mamo!, i adapted the solution in the link you gave me to my use case. I was able to retrieve the unique key and use that to write to the database at the same time saving a copy of the unique to that specific node of the database. As such when i wanted to delete, i just used that unique key. – nelsola Apr 28 '20 at 14:14