How can I delete images from firebase database? - android

I want to delete images from firebase storage.
This is my Firebase Database.

You need to use this method call:
StorageReference photoRef = mFirebaseStorage.getReferenceFromUrl(mImageUrl);
Then delete as you were:
photoRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted successfully
Log.d(TAG, "onSuccess: deleted file");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Log.d(TAG, "onFailure: did not delete file");
}});

Related

How to remove two documents in Firebase cloud database?

I wrote the following code that deletes two documents from the cloud Firebase database:
fireDB.document(groupPath).collection("users").document(phoneNumber).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
fireDB.collection("users").document(phoneNumber).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(this.getClass().getName(), "DocumentSnapshot successfully deleted");
Toast.makeText(getApplicationContext(),R.string.successfully_deleted_user,Toast.LENGTH_LONG).show();
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(this.getClass().getName(), "Error deleting document", e);
Toast.makeText(getApplicationContext(),R.string.failed_to_delete_user,Toast.LENGTH_LONG).show();
}
});
Log.d(this.getClass().getName(), "DocumentSnapshot successfully deleted");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(this.getClass().getName(), "Error deleting document", e);
Toast.makeText(getApplicationContext(),R.string.failed_to_delete_user,Toast.LENGTH_SHORT).show();
}
});
The problem with that code is that it deletes first document and then deletes second document, meaning if the first try will delete it successfully and the second one will fail to delete it, there is going to be a problem. Is it possible to delete two documents in Firebase cloud database so the result could be of of the following two options:
Both of the documents are deleted.
Both of the document are not deleted.
Is it possible to do?
As robsiemb commented, you'll want to use a batch write or transaction for this.
As far as I can see, the equivalent from your code would be something like this:
// Get a new write batch
WriteBatch batch = db.batch();
DocumentReference docRef1 = fireDB.document(groupPath).collection("users").document(phoneNumber);
DocumentReference docRef2 = fireDB.collection("users").document(phoneNumber)
DocumentReference laRef = db.collection("cities").document("LA");
batch.delete(docRef1);
batch.delete(docRef2);
// Commit the batch
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});

How to Delete value from Firebase realtime database by key in android?

I have realtime database in firebase it look like this
Now I want to delete value by key in android (java).
I have tried this code
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("coating").child("88").removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(activity, "on success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(activity, "on success"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
I get success response in onSuccess Method but value in database is not deleted.
As per this document
check out last para about delete and update ui

Upload an image to firebase for a specific user

How can I modify this code that can upload an image to firebase for a specific user, this creates a randomUUID. but I want to upload image under any specific UID:
StorageReference ref = storageReference.child("Profile/"+ UUID.randomUUID().toString());
ref.putFile(mainImageURI)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
setupProgress.setVisibility(View.INVISIBLE);
//progressDialog.dismiss();
Toast.makeText(SetupActivity.this, "Profile Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
setupProgress.setVisibility(View.INVISIBLE);
//progressDialog.dismiss();
Toast.makeText(SetupActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
setupProgress.setVisibility(View.VISIBLE);
//double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
//progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
You can create user profile in Cloud FireStore or RealTime DataBase for each new user that being created and save inside the name of the image, than use Firebase Storage to pull it out by image name.

Creating nested folders in firebase storage

I've got one FirebaseDatabase reference and two FirebaseStorage references in my class.
First StorageReference is ProductImages and second reference will be the push key that I'm going to get from the DatabaseReference.
But the problem is that when I'm uploading the images in the storage no second reference is created. All the images are being stored in the ProductImages reference.
Is there any fault in my code?
Is this a limitation of Firebase?
Or is there any other way to create nested folders in Firebase Storage programmatically?
I've attached the code :
private DatabaseReference productRef;
private StorageReference productImagesRef, imageRef;
productRef = FirebaseDatabase.getInstance.getReference().child("Products");
productImagesRef = FirebaseStorage.getInstance().getReference().child("ProductImages");
final String key = productRef.push().getKey();
imageRef = FirebaseStorage.getInstance().getReference().child("ProductImages").child(key);
imageRef.putFile(mainImageUri)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Toast.makeText(getActivity(), "Failed to upload!!! Try Again...", Toast.LENGTH_SHORT).show();
return;
}
})
.addOnSuccessListener(getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
mainImageUrl = taskSnapshot.getDownloadUrl();
}
});
imageRef.putFile(sideImageOneUri)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Toast.makeText(getActivity(), "Failed to upload!!! Try Again...", Toast.LENGTH_SHORT).show();
return;
}
})
.addOnSuccessListener( getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
sideImageOneUrl = taskSnapshot.getDownloadUrl();
}
});
Alright guys, I think I've got an acceptable answer. I created different references for different images that I'm storing. Code is following :
private DatabaseReference productRef;
private StorageReference productImagesRef, imageRef, mainImgRef, sideImgRef;
productRef = FirebaseDatabase.getInstance.getReference().child("Products");
productImagesRef = FirebaseStorage.getInstance().getReference().child("ProductImages");
final String key = productRef.push().getKey();
imageRef = FirebaseStorage.getInstance().getReference().child("ProductImages").child(key);
mainImgRef = imageRef.child(mainImageUri.getLastPathSegment());
sideImgRef = imageRef.child(sideImageOneUri.getLastPathSegment());
mainImgRef.putFile(mainImageUri)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Toast.makeText(getActivity(), "Failed to upload!!! Try Again...", Toast.LENGTH_SHORT).show();
return;
}
})
.addOnSuccessListener(getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
mainImageUrl = taskSnapshot.getDownloadUrl();
}
});
sideImgRef.putFile(sideImageOneUri)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Toast.makeText(getActivity(), "Failed to upload!!! Try Again...", Toast.LENGTH_SHORT).show();
return;
}
})
.addOnSuccessListener( getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
sideImageOneUrl = taskSnapshot.getDownloadUrl();
}
});
Try this:
productImagesRef.child(key).putFile(mainImageUri).....
productRef.child(key).putFile(sideImageOneUri)....
Hope this will help.

Deleting file from Firebase Storage using URL

I am trying to delete a file from Firebase Storage using the files URL.
My issue is that the getReferenceFromUrl() can not be resolved.
Sample code here:
StorageReference mStorageRef;
String storageurl = "http:sample"
mStorageRef = FirebaseStorage.getInstance().getReference();
StorageReference ref2 = mStorageRef.getReferenceFromUrl(storageurl);
ref2.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted successfully
Toast.makeText(getContext(), "file deleted", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onSuccess: deleted file");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Log.d(TAG, "onFailure: did not delete file");
}
});
StorageReference storageReference = FirebaseStorage.getInstance().getReferenceFromUrl("https://firebasestorage.googleapis.com/v0/b/***********************-5fac-45b6-bbda-ed4e8a3a62ab");
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted successfully
Log.e("firebasestorage", "onSuccess: deleted file");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Log.e("firebasestorage", "onFailure: did not delete file");
}
});
Snippet for Delete file from Firebase Storage Using URL:
StorageReference storageReference = FirebaseStorage.getInstance().getReferenceFromUrl("https://firebasestorage.googleapis.com/v0/b/***********************-5fac-45b6-bbda-ed4e8a3a62ab");
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Error
}
});
try this I have tried this and its working
String storageUrl = "Chat-Images/1498804025000.png";
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child(storageUrl);
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted successfully
Log.d(TAG, "onSuccess: deleted file");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Log.d(TAG, "onFailure: did not delete file");
}
});
In case you are using kotlin, this is the code:
val storageReference: StorageReference = FirebaseStorage.getInstance().getReferenceFromUrl(urifinal) //urifinal is a String variable with the url
storageReference.delete().addOnSuccessListener {
//File deleted
Log.d("storage", "Done")
}.addOnFailureListener {
//failed to delete
Log.d("storage", "error while deleting")
}
I think what you need is getStorage() to be able to use getReferenceFromUrl(),
eg:
FirebaseStorage.getInstance().getStorage().getReferenceFromUrl(fileURL);

Categories

Resources