I am trying to upload an image and a document to the firebase storage and upload the links created from both to the Real-Time DB, everything happening on a button's click.
But in the firebase DB, the links are not uploaded while the other text I upload along with them is there.
Storage upload code:
updata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//before uploading both the doc and img..
progressDialog.setTitle("Uploading Images");
progressDialog.show();
final UploadData uploadData=new UploadData();
if(ImgPathUri!=null){
StorageReference str=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(ImgPathUri));
str.putFile(ImgPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String ImgLink=uri.toString();
linkimg=ImgLink;
uploadData.setImgURL(linkimg);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(addEventActivity.this, "fucked ra", Toast.LENGTH_SHORT).show();
finished=false;
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}
if(DocPathUri!=null){
StorageReference storageReference1=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(DocPathUri));
storageReference1.putFile(DocPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String DocLink=uri.toString();
linkdoc=DocLink;
uploadData.setDocURL(linkdoc);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("TAG_FOR_FAILURE LOG", "On Failure: The exception", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finished=false;
Toast.makeText(addEventActivity.this, "doc fucked", Toast.LENGTH_SHORT).show();
}
});
}
progressDialog.dismiss();
String info=infoText.getText().toString();
String event=eventName.getText().toString();
uploadData.setName(event);
uploadData.setInfo(info);
//uploading the event name,info and other file links to the RTDB under the event name
databaseReference.child(event).setValue(uploadData);
}
});
}
Where updata is the button, UploadData is the class for holding those all those values...
After I click the button the image is stored in the Storage while the Database holds nothing but,
data {
name:"given name"
info:"given info"
}
while it has to have included the ImgLink and DocLink.
Where does it lose track?
Try this code
Declare this object globally
Uri uri;
Set uri when user fetches the Image from the gallery
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
jimg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here sUrl will have downloadURL
private void uploadImage() {
try {
final StorageReference ref = storageReference.child( UUID.randomUUID().toString() );
//uploads the image
ref.putFile( uri ).addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener( new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final Uri downloadUrl = uri;
sUrl = downloadUrl.toString();
}
} ).addOnFailureListener( new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
} );
}
} );
}catch (Exception e){}
}
Each onSuccess method is called asynchronously, after the call to the server has completed. Since this takes time, you main code continues, and this means you're writing to the database, before the download URL is available.
It's easiest to see this if you place some log statements in your code:
Log.i("STORAGE", "Starting to upload image data");
StorageReference storageReference1=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(DocPathUri));
storageReference1.putFile(DocPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.i("STORAGE", "Image data uploaded, getting download URL");
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.i("STORAGE", "Got download URL");
String DocLink=uri.toString();
linkdoc=DocLink;
uploadData.setDocURL(linkdoc);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("TAG_FOR_FAILURE LOG", "On Failure: The exception", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finished=false;
Toast.makeText(addEventActivity.this, "doc fucked", Toast.LENGTH_SHORT).show();
}
});
...
uploadData.setName(event);
uploadData.setInfo(info);
Log.i("STORAGE", "Writing info to database");
databaseReference.child(event).setValue(uploadData);
The output of this is:
Starting to upload image data
Writing info to database
Image data uploaded, getting download URL
Got download URL
This is probably not what you expected, but it is working as intended, and completely explains why the download URL isn't written to the database: by the time you write to the database, the download URL hasn't been loaded yet.
The solution to this problem is always the same: any code that requires the download URL, need to be inside the onSuccess method that gets called when the download URL is retrieved (or at least needs to be called from there).
So something like:
updata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//before uploading both the doc and img..
progressDialog.setTitle("Uploading Images");
progressDialog.show();
final UploadData uploadData=new UploadData();
if(ImgPathUri!=null){
StorageReference str=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(ImgPathUri));
str.putFile(ImgPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String ImgLink=uri.toString();
linkimg=ImgLink;
uploadData.setImgURL(linkimg);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(addEventActivity.this, "fucked ra", Toast.LENGTH_SHORT).show();
finished=false;
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}
if(DocPathUri!=null){
StorageReference storageReference1=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(DocPathUri));
storageReference1.putFile(DocPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String DocLink=uri.toString();
linkdoc=DocLink;
uploadData.setDocURL(linkdoc);
progressDialog.dismiss();
String info=infoText.getText().toString();
String event=eventName.getText().toString();
uploadData.setName(event);
uploadData.setInfo(info);
//uploading the event name,info and other file links to the RTDB under the event name
databaseReference.child(event).setValue(uploadData);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("TAG_FOR_FAILURE LOG", "On Failure: The exception", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finished=false;
Toast.makeText(addEventActivity.this, "doc fucked", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
This is my code.
private void uploadPattern() {
if (mImageUri != null) {
final StorageReference fileReference = mStorageRef.child(System.currentTimeMillis() + "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(PatternArranger.this, "Save Successful", Toast.LENGTH_SHORT).show();
//Upload upload = new Upload(mEditPatternName.getText().toString().trim(),
//taskSnapshot.getUploadSessionUri().toString());
//String uploadId = mDatabaseRef.push().getKey();
//mDatabaseRef.child(uploadId).setValue(upload);
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while ( !urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
//Log.d(TAG, "onSuccess: firebase download url: " + downloadUrl.toString()); //use if testing...don't need this line.
Upload upload = new Upload(mEditPatternName.getText().toString().trim(),downloadUrl.toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(PatternArranger.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No pattern selected", Toast.LENGTH_SHORT).show();
}
}
By using a while loop, you are likely missing out on important debugging information to solve your issue. In your code, it is likely that urlTask has failed and urlTask.isSuccessful() will never evaluate to true which is causing an infinite loop.
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while ( !urlTask.isSuccessful());
To fix this, properly attach listeners to the Task returned by each operation and log their results.
taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUri) {
Log.d(TAG, "getDownloadUrl.onSuccess: obtained download URI: " + downloadUri.toString());
Upload upload = new Upload(mEditPatternName.getText().toString().trim(),downloadUri.toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload)
.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess() {
Log.d(TAG, "setValue.onSuccess: uploaded & saved to database");
// TODO: Update UI to show image/completion message
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Log.d(TAG, "setValue.onFailure: error occured - " + exception.message);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Log.d(TAG, "getDownloadUrl.onFailure: error occured - " + exception.message);
}
});
I am trying to replace an image in Firebase storage with a new one by first deleting the old and then adding the new. The problem is the deletion. I cannot seem to get it to work. Here is the relevant code:
private void uploadFile(){
progressBar.setVisibility(View.VISIBLE);
db2 = FirebaseFirestore.getInstance().collection("Users").document(id);
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "."+ getFileExtension(imageuri));
mUploadTask = fileReference.putFile(imageuri).
addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
db2.update("Image URI",downloadUrl.toString()).addOnSuccessListener(
new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(settings_activity
.this, "DP change added." ,
Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(settings_activity.this, "FIRESTROE ERROR "+e.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(settings_activity.this, "FILE STRORAGE "+e.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(settings_activity.this, "DELETION ERROR: "+e.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
This is the storage reference I used in the code above:
FirebaseStorage.getInstance().getReference().child("profile_pics/"+FirebaseAuth.getInstance().getCurrentUser().getUid());
How can I push the download URL of Firebase storage files to the Firestore cloud? I have a project that can upload PDF files to Firestore storage, but I can't push the download URL of the uploaded files to the Firestore cloud.
I need to catch the upload URL for every single file and send it to the document in the firestore to be able to download it. I'm uploading and downloading PDF files.
Here is my code:
public class pdfUploader extends AppCompatActivity {
private StorageReference mStorageRef;
Button upload;
Button select;
int CODE=215;
private CollectionReference dbFirestore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_uploader);
mStorageRef = FirebaseStorage.getInstance().getReference();
upload = findViewById(R.id.upload);
select = findViewById(R.id.choose);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectFile();
}
});
}
public void selectFile () {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i,"Select a file"), CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String filePath = data.getDataString();
Uri SelectedFileLocation=Uri.parse(filePath);
UploadFile(SelectedFileLocation);
super.onActivityResult(requestCode, resultCode, data);
}
public void UploadFile( Uri file) {
Toast.makeText(this, "Please wait.. the file is uploading!", Toast.LENGTH_SHORT).show();
//Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = mStorageRef.child(Objects.requireNonNull(file.getLastPathSegment()));
riversRef.putFile(file)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(pdfUploader.this, "Upload Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(pdfUploader.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
});
}
}
Assign this Variable on Top
FirebaseFirestore db;
//In oncreateView we have to assign now db so.
db = FirebaseFirestore.getInstance();
Code for get File uri :
riversRef.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
riversRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
//After upload Complete we have to store the Data to firestore.
Map<String, Object> file = new HashMap<>();
file.put("url", downloadUrl.toString()); // We are using it as String because our data type in Firestore will be String
db.collection("/*Put you're collection name*/").document("/*And Document name Here*/")
.set(file)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
}
}
});
If download url expires there's better way to store you're image file in you're storage and firestore
Code :
riversRef.putFile(file)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String path = //Put path of storage it will be something like [images/filename.jpg(Put your extension of file)] this path from firebase storage
Map<String, Object> file = new HashMap<>();
file.put("url", path); // We are using it as String because our data type in Firestore will be String
db.collection("/*Put you're collection name*/").document("/*And Document id Here*/")
.set(file)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(pdfUploader.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
});
the above code will be useful and better when you're dealing with images and read this docs for further details
private void uploadImageToFirebaseStorage() {
StorageReference profileImageRef =
FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");
if (uriProfileImage != null) {
progressBar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.GONE);
profileImageUrl = taskSnapshot.**getDownloadUrl**().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(ProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
taskSnapshot.getDownloadUrl() method not working comes up with red line under it
Edit: see this comment on why the approach in this answer doesn't work:
firebaser here This answer is wrong. While it at first may appear to work (since it compiles) the result of getDownloadUrl().toString() is not a download URL, but a string representation of a Task object. For a better answer, see stackoverflow.com/a/55503926 or the sample in the Firebase documentation.
Original answer below...
In Firebase Storage API version 16.0.1,
the getDownloadUrl() method using taskSnapshot object has changed.
now you can use,
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
to get download url from the firebase storage.
To get imageUrl path from storage use this code:
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if (taskSnapshot.getMetadata() != null) {
if (taskSnapshot.getMetadata().getReference() != null) {
Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String imageUrl = uri.toString();
//createNewPost(imageUrl);
}
});
}
}
}});
that is all 😉
NOTE: Do not forget initialize StorageReference and UploadTask in your uploadFile method.
Try Using this it will download the image from FireBase storage
FireBase Libraries versions 16.0.1
Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String photoStringLink = uri.toString();
}
});
I faced the similar error I solved it with this method. Hope it helps
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> task = taskSnapshot.getMetadata().getReference().getDownloadUrl();
task.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String photoLink = uri.toString();
Map userInfo = new HashMap();
userInfo.put("profileImageUrl", photoLink);
mUserDatabase.updateChildren(userInfo);
}
});
finish();
return;
}
});
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
changeProfilePic(String.valueOf(task.getResult()));//gives image or file string url
}
});
try this code will work for sure
My Google Firebase Plugins in build.gradle(Module: app):
implementation 'com.firebaseui:firebase-ui-database:3.3.1'
implementation 'com.firebaseui:firebase-ui-auth:3.3.1'
implementation 'com.google.firebase:firebase-core:16.0.0'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-auth:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.0.1'
build.gradle(Project):
classpath 'com.google.gms:google-services:3.2.1'
My upload() function and fetching uploaded data from Firebase storage :
private void upload() {
if (filePath!=null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child(new StringBuilder("images/").append(UUID.randomUUID().toString()).toString());
uploadTask = ref.putFile(filePath);
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 ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
progressDialog.dismiss();
// Continue with the task to get the download URL
saveUrlToCategory(downloadUri.toString(),categoryIdSelect);
} else {
Toast.makeText(UploadWallpaper.this, "Fail UPLOAD", Toast.LENGTH_SHORT).show();
}
}
}).addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
progressDialog.setMessage("Uploaded: ");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(UploadWallpaper.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
FOR THOSE WHO ARE USING LATEST FIREBASE VERSION taskSnapshot.getDownloadUrl() method is DEPRECATED or OBSOLETE !!
I'm using Firebase Storage API version 16.0.5 and the task has to be referenced as
someTask.getResult().getMetadata().getReference().getDownloadUrl().toString();
hope this helps!
You wont get the download url of image now using
profileImageUrl = taskSnapshot.**getDownloadUrl**().toString();
this method is deprecated.
Instead you can use the below method
uniqueId = UUID.randomUUID().toString();
ur_firebase_reference = storageReference.child("user_photos/" + uniqueId);
Uri file = Uri.fromFile(new File(mphotofile.getAbsolutePath()));
UploadTask uploadTask = ur_firebase_reference.putFile(file);
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();
}
// Continue with the task to get the download URL
return ur_firebase_reference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
System.out.println("Upload " + downloadUri);
Toast.makeText(mActivity, "Successfully uploaded", Toast.LENGTH_SHORT).show();
if (downloadUri != null) {
String photoStringLink = downloadUri.toString(); //YOU WILL GET THE DOWNLOAD URL HERE !!!!
System.out.println("Upload " + photoStringLink);
}
} else {
// Handle failures
// ...
}
}
});
//upload button onClick
public void uploadImage(View view){
openImage()
}
private Uri imageUri;
ProgressDialog pd;
//Call open Image from any onClick Listener
private void openImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMAGE_REQUEST);
}
private void uploadImage(){
pd = new ProgressDialog(mContext);
pd.setMessage("Uploading...");
pd.show();
if (imageUri != null){
final StorageReference fileReference = storageReference.child(userID
+ "."+"jpg");
// Get the data from an ImageView as bytes
_profilePicture.setDrawingCacheEnabled(true);
_profilePicture.buildDrawingCache();
//Bitmap bitmap = ((BitmapDrawable) _profilePicture.getDrawable()).getBitmap();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = fileReference.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
pd.dismiss();
Log.e("Data Upload: ", "Failled");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
// ...
Log.e("Data Upload: ", "success");
Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String downloadLink = uri.toString();
Log.e("download url : ", downloadLink);
}
});
pd.dismiss();
}
});
}else {
Toast.makeText(getApplicationContext(),"No Image Selected", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null;
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
imageUri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);
_profilePicture1.setImageBitmap(bitmap);
_profilePicture1.setDrawingCacheEnabled(true);
_profilePicture1.buildDrawingCache();
} catch (IOException e) {
e.printStackTrace();
}
if (uploadTask != null && uploadTask.isInProgress()){
Toast.makeText(mContext,"Upload in Progress!", Toast.LENGTH_SHORT).show();
}
else {
try{
uploadImage();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
taskSnapshot.**getDownloadUrl**().toString(); //deprecated and removed
use below code for downloading Url
final StorageReference profileImageRef= FirebaseStorage.getInstance().getReference("profilepics/" + "abc_10123" + ".jpg");
profileImageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
#Override
public void onSuccess(Uri downloadUrl)
{
//do something with downloadurl
}
});
for latest version try
profileImageUrl = taskSnapshot.getStorage().getDownloadUrl().toString();
Try using this:
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
FirebaseStorage Library version 19.0.1 works with
String download_image_path = task.getResult().getUploadSessionUri().toString();
//firebase database
implementation 'com.google.firebase:firebase-database:15.0.0'
//firebase storage
implementation 'com.google.firebase:firebase-storage:15.0.0'
.getDownloadUrl() method is removed from later versions , i have changed it to 15.0.0 and works perfectly fine.You can find these in build.gradle(module:app)
Only that...
taskSnapshot.getStorage().getDownloadUrl();
Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String photoStringLink = uri.toString();
mDatavaseRef.push().setValue(photoStringLink);
}
});
This will work:
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String photoStringLink = uri.toString();
Log.i("urlimage", photoStringLink);
}
});
}
});
Try this:
Uri download_uri ;
final Map<String, String> userData = new HashMap<>();
if (task != null) {
//download_uri = task.getResult().getDownloadUrl();
download_uri = task.getResult().getUploadSessionUri();
}
else {
download_uri= imageUri;
}
userData.put("Image", download_uri.toString());
userData.put("name",username);
userData.put("category",category);
userData.put("status",status);
this is help help me with the last dependencies in 04/2020
// Get a reference to store file at chat_photos/<FILENAME>
final StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
photoRef.putFile(selectedImageUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//When the image has successfully uploaded, get its downloadURL
photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri dlUri = uri;
FriendlyMessage friendlyMessage = new
FriendlyMessage(null, mUsername, dlUri.toString());
Use Firebase storage version 15.0.0.
Uri downloadUrl=taskSnapshot.getDownloadUrl().toString();
you can also use Picasso dependencies . its easy to use for uploading image in firebase.
ActivityFile:
Picasso.get().load(uriImage).into(ImageUri);
app-gradle:
com.squareup.picasso:picasso:2.71828
This will Solve Your Problem....
if(uploadTask.isSuccessfull()){
Task<Uri> uriTask=uploadTask.getResult().getStorage().getDownloadUrl(); while(!uriTask.isSuccessful());
Uri downloadUri=uriTask.getResult();
final String download_url=downloadUri.toString();
}
private void uploadImageTask() {
Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/Pictures/OnShot.jpg"));
StorageReference storageReference = this.storageReference.child("images/" + UUID.randomUUID().toString());
storageReference.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
Log.d(TAG, "Download URL: " + String.valueOf(task.getResult()));
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
I still having this error. What might be wrong? I already changed the permissions, and users to anonymous.
For Java Code
String downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
For Kotlin
val downloadUrl = taskSnapshot.getMetadata()?.getReference()?.getDownloadUrl()?.toString()
there is nothing wrong with the depencies. You just have to downgrade your firebase depencies. This is because it hasnt been updated yet..