This question already has answers here:
How to get URL from Firebase Storage getDownloadURL
(13 answers)
How to get the download url from Firebase Storage?
(1 answer)
Closed 3 years ago.
I am retrieving the download URL from a song file that is stored in firebase storage.The URL that i am getting is not the same URL that is in the firebase storage.
Here is the wrong link i get: com.google.android.gms.tasks.zzu#75f559a
Here is the correct link: https://firebasestorage.googleapis.com/v0/b/fouronesixsound-51999.appspot.com/o/Uploads%2F1221?alt=media&token=56beacd5-9abd-4a74-b294-69eb111fcb00
Here is a link to a picture of my database setup:
https://imgur.com/a/Gtl1ThZ
This is my code:
final String fileName = songUri.getLastPathSegment() + "";
//final String fileName1=songUri.getLastPathSegment()+"";
final StorageReference storageRef = storage.getReference();
storageRef.child("Uploads").child(fileName).putFile(songUri)
.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String url =
storageRef.child("Uploads").child(fileName).getDownloadUrl().toString();
//returns the url of the uploaded file
DatabaseReference reference = database.getReference();
reference.child("Uploads").child(fileName).setValue(url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
Toast.makeText(Upload.this, "File Uploaded Successfully", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Upload.this, "Upload failed", Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Upload.this, "Upload failed",Toast.LENGTH_SHORT).show();
}
storageRef.child("Uploads").child(fileName).getDownloadUrl(); returns a Task object, not Uri directly. You have to add completion listener to this task and then upload the url to your database.
final String fileName = songUri.getLastPathSegment() + "";
//final String fileName1=songUri.getLastPathSegment()+"";
final StorageReference storageRef = storage.getReference();
storageRef.child("Uploads").child(fileName).putFile(songUri)
.addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageRef.child("Uploads").child(fileName).getDownloadUrl()
.addOnCompleteListener(new OnCompleteListener < Uri > () {
#Override
public void onComplete(#NonNull Task < Uri > task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
reference.child("Uploads").child(fileName).setValue(downloadUri.toString()).addOnCompleteListener(new OnCompleteListener < Void > () {
#Override
public void onComplete(#NonNull Task < Void > task) {
if (task.isSuccessful())
Toast.makeText(Upload.this, "File Uploaded Successfully", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Upload.this, "Upload failed", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(Upload.this, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Upload.this, "Upload failed", Toast.LENGTH_SHORT).show();
}
Related
Here i added the code which i'm working on. i tried as said in doc but image get uploaded in Firebase Storage but the Uri is not get updated in Cloud Firestore database. what am i missing.?
java file:
fAuth.createUserWithEmailAndPassword(email.getText().toString(),password.getText().toString()).addOnSuccessListener(authResult -> {
FirebaseUser user =fAuth.getCurrentUser();
Toast.makeText(Register.this, "Account Created",Toast.LENGTH_SHORT).show();
StorageReference Image_path = sRef.child("Profile_Images").child(user.getUid() + ".jpg");
Image_path.putFile(mainImageURI).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Image_path.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri download_uri = uri;
DocumentReference sc=fStore.collection("image").document(user.getUid());
Map<String,String> useInfo = new HashMap<>();
useInfo.put("Profile Pic",download_uri.toString());
sc.set(useInfo);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
String setupError = e.getMessage();
Toast.makeText(Register.this, "IMAGE Error : " + setupError, Toast.LENGTH_LONG).show();
}
});
Rule:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
Adding complete listener to the set()
fStore.collection("Users").document(user.getUid()).set(useInfo).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(Register.this, "Account Created", Toast.LENGTH_LONG).show();
}else{
String error = task.getException().getMessage();
Toast.makeText(Register.this, "FireStore Error : " + error, Toast.LENGTH_LONG).show();
}
}
});
} else {
// Handle failures
String error = task.getException().getMessage();
Toast.makeText(Register.this, "FireStore Error : " + error, Toast.LENGTH_LONG).show();
}
This question already has an answer here:
getDownloadURL isn't inputting the link i need
(1 answer)
Closed 2 years ago.
I'm trying to upload an image to Firebase Storage and after that send the URL of this image to Firebase Database. The Uri is correct, but when I try to set it on my object, the method singleDetection.setImage(imagePath) is setting nothing. Here is my code:
Bitmap image = detectedFaceItems.get(0).getImage();
StorageReference storageRef = storage.getReference();
StorageReference imagesRef = storageRef.child("2.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
StorageTask<UploadTask.TaskSnapshot> uploadTask = imagesRef.putBytes(data)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to sent a file", Toast.LENGTH_LONG).show();
}
})
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "Successfully sent a file", Toast.LENGTH_LONG).show();
storageRef.child("2.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
//Doesn't work corretly
String imagePath = uri.toString();
singleDetection.setImage(imagePath);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to get an Uri", Toast.LENGTH_LONG).show();
}
});
}
});
You are uploading the image right, but your call to Firebase after successfully uploading the image using storageRef.child("2.jpg").getDownloadUrl(). not that right as you already don't know the generated Uri which you can get from the snapshot that is returned back with the taskSnapshot.
So replace the below part of code:
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "Successfully sent a file", Toast.LENGTH_LONG).show();
storageRef.child("2.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
//Doesn't work corretly
String imagePath = uri.toString();
singleDetection.setImage(imagePath);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to get an Uri", Toast.LENGTH_LONG).show();
}
});
}
});
With:
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// get upload url
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String imagePath = String.valueOf(task.getResult());
singleDetection.setImage(imagePath);
}
});
}
});
Note: here you've uploaded the image itself, but don't upload its Uri, so you can to decide to upload it to firebase as you'd like.
Whenever I'm trying to upload a file to firebase storage, and then retrieve the download URL for it, I'm getting the same URL even when different files are uploaded. The files do get uploaded, but the URL received is similar for every upload
downloadURL = new Uri[1];
UploadTask uploadTask = mChatPhotosStorageReference
.child(selectedImageUri.getLastPathSegment())
.putFile(selectedImageUri);
Log.v("SelectedImage: ", selectedImageUri.getLastPathSegment());
uploadTask
.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful())
throw task.getException();
return mChatPhotosStorageReference.getDownloadUrl();
}
})
.addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
downloadURL[0] = task.getResult();
//passing downloadUri to database to store with chat messages
ShutUpMessages shutUpMessages = new ShutUpMessages(null, mUsername, downloadURL[0].toString());
mMessagesDatabaseReference.push().setValue(shutUpMessages);
mProgressbar.setVisibility(ProgressBar.INVISIBLE);
Toast.makeText(MainActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(MainActivity.this, "File Upload failed", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_SHORT).show();
mProgressbar.setVisibility(ProgressBar.INVISIBLE);
}
});
I'm creating an app like olx, Where if you upload ad , its gets posted in two different collections, namly "My Ads" where ads of every logged in user are posted against his ID, and Explore collection Where ads are posted for all users. So if i want to update or delete ad, It should be deleted from both collections! Image Url :https://imgur.com/a/HCKfGBb
String uid= user.getUid();
SellingDetails.put("uid",uid);
final CollectionReference reference = exploreAdDB.collection("cities/" + city + "/" + category);
final CollectionReference myAdDocRef = myAdDB.collection("users/ads/"+uid);
if (imageUri != null) {
final StorageReference fileReference = mStorage.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
UploadTask uploadTask = fileReference.putFile(imageUri);
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
if(downloadUri!=null)
SellingDetails.put("imageUrl",downloadUri.toString());
reference.add(SellingDetails).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(GetLocationActivity.this, "Service Uploaded in explore db ", Toast.LENGTH_SHORT).show();
pgAd.setVisibility(View.INVISIBLE);
Intent intent = new Intent(GetLocationActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
Toast.makeText(GetLocationActivity.this, "Ad posted Successfully", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(GetLocationActivity.this, "Failed adding data into explore db", Toast.LENGTH_SHORT).show();
pgAd.setVisibility(View.INVISIBLE);
}
});
myAdDocRef.add(SellingDetails).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(GetLocationActivity.this, "Data Also added to myAds db", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(GetLocationActivity.this, "Data not added into my ads", Toast.LENGTH_SHORT).show();
}
});
} else {
// Handle failures
Toast.makeText(GetLocationActivity.this, "Failed adding data", Toast.LENGTH_SHORT).show();
}
}
});
}
In my app user can upload their image in Firebase storage and database via my app, but i cant retrieve URL of uploaded image to set their profile Image
private FirebaseAuth mAuth;
private DatabaseReference databaseReference;
private StorageReference UserProfileImageRef;
String currentUserID;
databaseReference=FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
UserProfileImageRef=FirebaseStorage.getInstance().getReference().child("Profile Images");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{
String q=UserProfileImageRef.getDownloadUrl().toString();
Toast.makeText(SetupActivity.this, "url"+q, Toast.LENGTH_SHORT).show();
Glide.with(SetupActivity.this)
.load(q)
.into(ProfileImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
enter image description hereenter code here
databaseReference=FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID).child("profileimage");
You forgot to add the child "profileimage"
UPDATE:
Your download url is not same as in the Firebase Storage. I assumed you take the wrong download url.
Refer to this link: https://stackoverflow.com/a/50572357/9346054
filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.d(TAG, "onSuccess: uri= "+ uri.toString());
//You store the download in database.
//set value databaseReference=FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID).child("profileimage").setValue(uri.toString()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
//Success store the link in the database.
Toast.makeText( getApplicationContext(), "Success",Toast.LENGTH_SHORT ).show();
}
}
});
}
});
}
});
UPDATE BASE ON UR ANSWER:
try this one
Uri resulturi = result.getUri();
final StorageReference filepath = UserProfileImageRef.child(currentUserID + ".jpg");
filepath.putFile(resulturi).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
//Okay part ni dia ambik link kat firebase storage akan pergi ke photoUri kat student tuu
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Update in database
databaseReference.child("profileimage").setValue(String.valueOf(uri));
Toast.makeText(SetupActivity.this, "successfully", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
});
Uri resulturi=result.getUri();
StorageReference filepath=UserProfileImageRef .child(currentUserID +".jpg");
filepath.putFile(resulturi).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task)
{
if (task.isSuccessful())
{
Intent selfIntent=new Intent(SetupActivity.this,SetupActivity.class);
startActivity(selfIntent);
Toast.makeText(SetupActivity.this, "success", Toast.LENGTH_SHORT).show();
final String downloadurl =task.getResult().getStorage().getDownloadUrl().toString();
databaseReference.child("profileimage").setValue(downloadurl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(SetupActivity.this, "successfully", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
else
{
String message=task.getException().getMessage();
Toast.makeText(SetupActivity.this, "error"+message, Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
}
});
}