Issue
I have an app, that has many users they are all stored in Realtime Database. I'm trying to delete user on button click with all the data, but the profile pictures are still left in Firebase Storage after deletion. So when I try to delete the picture from Firebase Storage aswell as users I get this error. User does not have permission to access this object.
So I'm trying to delete picture in the ValueEventListener method, because I can easily get the ImageURL from my Realtime Database.
Realtime Database
In DB I have attribute profileimage: GeneratedPictureUrlWhenUploadingToStorage Also my pictures in Firebase Storage are named currentUserId + ".JPG" so its like an indetifer
Storage Rules:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
Code:
switch (view.getId()){
case R.id.buttonEditProfile:
startActivity(new Intent(this, ProfileEditActivity.class));
break;
case R.id.buttonUserList:
startActivity(new Intent(this, UserListActivity.class));
break;
case R.id.buttonDeleteAccount:
profileUserRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
StorageReference storageReference1;
String myImage = dataSnapshot.child("profileimage").getValue().toString();
storageReference1 = FirebaseStorage.getInstance().getReferenceFromUrl(myImage);
storageReference1.delete();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
DatabaseReference drFailure = FirebaseDatabase.getInstance().getReference("failures").child(currentUserId);
DatabaseReference drVehicles = FirebaseDatabase.getInstance().getReference("vehicles").child(currentUserId);
DatabaseReference drUsers = FirebaseDatabase.getInstance().getReference("users").child(currentUserId);
FirebaseUser userDel = FirebaseAuth.getInstance().getCurrentUser();
drFailure.removeValue();
drVehicles.removeValue();
drUsers.removeValue();
userDel.delete();
When I press the buttonDeleteAccount I want to delete Storaged pictures of uniqe User
Solution
If you are getting an error with permission, maybe the storage rules is blocking your access.
Also try to delete the file using your file name logic. Like:
StorageReference storageRef = storage.getReference();
StorageReference photoRef = storageRef.child("YOUR_PATH" + userId + ".jpg");
photoRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// Success
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Error
}
});
Answered By - William
Answer Checked By - David Marino (JavaFixing Volunteer)