Gastón Saillén
Gastón Saillén

Reputation: 13129

Firebase won't delete files after database erase

I have a database with, let's say, 300 links of files. Those files are stored in my storage, and if I go manually delete the database tree with all the links, the files are still in the storage, and after that if the user keeps uploading files. The links and new files are generated but I'm keeping the old files too. Is there a way that if I delete from the database tree my files links and children will them be deleted from the storage too?

I was really thinking about this because I think is a little mess to debug erasing the database manually from the site, but the files are still there.

Upvotes: 0

Views: 294

Answers (2)

Moz
Moz

Reputation: 119

Just call the methods individually or make sure the FirebaseStorage operation is the last method to be called when invoking .addOnCompleteListener(...) or .continueWithTask(...) on the returned Task object.

For example:

FirebaseDatabase.getInstance().getReference().child("Users").child("user-123").child("photo").removeValue();
FirebaseStorage.getInstance().getReference().child("Users").child("user-123").child("photo").delete();

OR

FirebaseDatabase.getInstance().getReference().child("Users").child("user-123").child("photo").removeValue().continueWithTask(new Continuation<Void, Task<Void>>() {
                                                    @NonNull
                                                    @Override
                                                    public Task<Void> then(@NonNull Task<Void> removePhotoTaskInFirebaseUser) throws Exception {
                                                        return FirebaseStorage.getInstance().getReference().child("Users").child("user-123").child("photo").delete();
                                                    }
                                                }).addOnCompleteListener(...);

Upvotes: 0

Alex Mamo
Alex Mamo

Reputation: 138824

Assuming you have a database which looks like this:

Firebase-database
    |
    --- links
          |
          --- linkId1: "http://..."
          |
          --- linkId2: "http://..."
          |
          --- linkId3: "http://..."

To delete all the files from Firebase Storage that correspond to those links, please use the following code:

StorageReference storageRef = storage.getReference();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference linksRef = rootRef.child("links");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String link = ds.getValue(String.class);
            storageRef.child(link).delete();
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
linksRef.addListenerForSingleValueEvent(eventListener);

Upvotes: 1

Related Questions