Posted image is not appearing in Firebase Recycler View - java

I am trying to retrieve all users posts from firebase database and want to display it on Main Activity with the help Recycler View and Firebase Recycler Adapter.
But After Successfully Uploading The Image to Firebase database , i can see the uploaded image in storage section of firebase console but in database section it's showing something like -
com.google.android.gms.tasks.zzu#3c50f45
So I think the problem is with this line of code :
downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
CODE:
private Uri ImageUri;
private StorageReference PostsImagesRefrence;
private DatabaseReference UsersRef, PostsRef;
PostsImagesRefrence = FirebaseStorage.getInstance().getReference();
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
StorageReference filePath = PostsImagesRefrence.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>()
{
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task)
{
if(task.isSuccessful())
{
downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
Toast.makeText(PostActivity.this, "image uploaded successfully to Storage...", Toast.LENGTH_SHORT).show();
SavingPostInformationToDatabase();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(PostActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
}
}
});
Design View And Actual Output Image:
Design View
View After Running
Please Try To provide me a correct code , help me as i am a newbie and don't know about Android Studio , and want to complete this College Project.

Try changing
String userFullName = dataSnapshot.child("fullname").getValue().toString();
String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();
To
String userFullName = dataSnapshot.child("fullname").getValue(String.class);
String userProfileImage = dataSnapshot.child("profileimage").getValue(String.class);
EDIT: Try this
dateRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUrl)
{
downloadUrlString = downloadUrl.toString();
}
});

Solved It , I was using old method for storing the image to firebase database.
Following changes has been done to solve it :
final StorageReference filePath = PostsImagesRefrence.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
final UploadTask uploadTask =filePath.putFile(ImageUri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e)
{
String message =e.toString();
Toast.makeText(PostActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>()
{
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Toast.makeText(PostActivity.this, "Image uploaded successfully to Storage...", Toast.LENGTH_SHORT).show();
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();
}
downloadUrl= filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>()
{
#Override
public void onComplete(#NonNull Task<Uri> task)
{
if (task.isSuccessful())
{
downloadUrl = task.getResult().toString();
Toast.makeText(PostActivity.this, "Stored Image Successfully to Database", Toast.LENGTH_SHORT).show();
SavingPostInformationToDatabase();
}
}
});
}

Related

Image being saved as com.google.android.gms.tasks.zzu# in firebase database, I still don't know how to fix after reading other posts [duplicate]

I'm trying to get the "long term persistent download link" to files in our Firebase storage bucket.
I've changed the permissions of this to
service firebase.storage {
match /b/project-xxx.appspot.com/o {
match /{allPaths=**} {
allow read, write;
}
}
}
And my javacode looks like this:
private String niceLink (String date){
String link;
// Points to the root reference
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference dateRef = storageRef.child("/" + date+ ".csv");
link = dateRef.getDownloadUrl().toString();
return link;
}
When I run this I get the uri link that looks something like
com.google.android.gms.tasks.zzh#xxx
Question 1. Can I from this get the download link similar to: https://firebasestorage.googleapis.com/v0/b/project-xxxx.appspot.com/o/20-5-2016.csv?alt=media&token=b5d45a7f-3ab7-4f9b-b661-3a2187adxxxx
When trying to get the link above I changed the last row before my return, like this:
private String niceLink (String date){
String link;
// Points to the root reference
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference dateRef = storageRef.child("/" + date+ ".csv");
link = dateRef.getDownloadUrl().getResult().toString();
return link;
}
But when doing this i get a 403 error, and the app crashing. The consol tells me this is bc user is not logged in /auth.
"Please sign in before asking for token"
Question 2. How do I fix this?
Please refer to the documentation for getting a download URL.
When you call getDownloadUrl(), the call is asynchronous and you must subscribe on a success callback to obtain the results:
// Calls the server to securely obtain an unguessable download Url
private void getUrlAsync (String date){
// Points to the root reference
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference dateRef = storageRef.child("/" + date+ ".csv");
dateRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
#Override
public void onSuccess(Uri downloadUrl)
{
//do something with downloadurl
}
});
}
This will return a public unguessable download url. If you just uploaded a file, this public url will be in the success callback of the upload (you do not need to call another async method after you've uploaded).
However, if all you want is a String representation of the reference, you can just call .toString()
// Returns a Uri of the form gs://bucket/path that can be used
// in future calls to getReferenceFromUrl to perform additional
// actions
private String niceRefLink (String date){
// Points to the root reference
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference dateRef = storageRef.child("/" + date+ ".csv");
return dateRef.toString();
}
//Firebase Storage - Easy to Working with uploads and downloads.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RC_SIGN_IN){
if(resultCode == RESULT_OK){
Toast.makeText(this,"Signed in!", LENGTH_SHORT).show();
} else if(resultCode == RESULT_CANCELED){
Toast.makeText(this,"Signed in canceled!", LENGTH_SHORT).show();
finish();
}
} else if(requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK){
// HERE I CALLED THAT METHOD
uploadPhotoInFirebase(data);
}
}
private void uploadPhotoInFirebase(#Nullable Intent data) {
Uri selectedImageUri = data.getData();
// Get a reference to store file at chat_photos/<FILENAME>
final StorageReference photoRef = mChatPhotoStorageReference
.child(selectedImageUri
.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Download file From Firebase Storage
photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadPhotoUrl) {
//Now play with downloadPhotoUrl
//Store data into Firebase Realtime Database
FriendlyMessage friendlyMessage = new FriendlyMessage
(null, mUsername, downloadPhotoUrl.toString());
mDatabaseReference.push().setValue(friendlyMessage);
}
});
}
});
}
here i am uploading and getting the image url at the same time...
final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");
if (uriProfileImage != null) {
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// profileImageUrl taskSnapshot.getDownloadUrl().toString(); //this is depreciated
//this is the new way to do it
profileImageRef.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String profileImageUrl=task.getResult().toString();
Log.i("URL",profileImageUrl);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(ProfileActivity.this, "aaa "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
For me, I did my code in Kotlin and I had the same error "getDownload()". Here are both the dependencies that worked for me and the Kotlin code.
implementation 'com.google.firebase:firebase-storage:18.1.0' firebase storage dependencies
This what I added and it worked for me in Kotlin. Storage() would come before Download()
profileImageUri = taskSnapshot.storage.downloadUrl.toString()
StorageReference mStorageRef = FirebaseStorage.getInstance().getReference();
final StorageReference fileupload=mStorageRef.child("Photos").child(fileUri.getLastPathSegment());
UploadTask uploadTask = fileupload.putFile(fileUri);
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();
Picasso.get().load(downloadUri.toString()).into(image);
} else {
// Handle failures
}
}
});
Clean And Simple
private void putImageInStorage(StorageReference storageReference, Uri uri, final String key) {
storageReference.putFile(uri).addOnCompleteListener(MainActivity.this,
new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
task.getResult().getMetadata().getReference().getDownloadUrl()
.addOnCompleteListener(MainActivity.this,
new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
FriendlyMessage friendlyMessage =
new FriendlyMessage(null, mUsername, mPhotoUrl,
task.getResult().toString());
mFirebaseDatabaseReference.child(MESSAGES_CHILD).child(key)
.setValue(friendlyMessage);
}
}
});
} else {
Log.w(TAG, "Image upload task was not successful.",
task.getException());
}
}
});
}
The getDownloadUrl method was removed in firebase versions greater than 11.0.5
I recommend using version 11.0.2 that still uses this method.
The getDownloadUrl method has now been depreciated in the new firebase update. Instead use the following method.
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
change the received URI to URL
val urlTask = uploadTask.continueWith { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
spcaeRef.downloadUrl
}.addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUri = task.result
//URL
val url = downloadUri!!.result
} else {
//handle failure here
}
}
You can Upload images to firestore and get it's download URL as below function:
Future<String> uploadPic(File _image) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
var downloadURL = await(await uploadTask.onComplete).ref.getDownloadURL();
var url =downloadURL.toString();
return url;
}
Also you can do as follows In latest Firebase_storage version nullsafe,
//Import
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
Future<void> _downloadLink(firebase_storage.Reference ref) async {
//Getting link make sure call await to make sure this function returned a value
final link = await ref.getDownloadURL();
await Clipboard.setData(ClipboardData(
text: link,
));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Success!\n Copied download URL to Clipboard!',
),
),
);
}
implementation 'com.google.firebase:firebase-storage:19.2.0'
Recently getting url from upload task wasn't working so I tried this and worked for me on above dependency.
So inside where you use firebase upload method use this.
filepath is the reference of Firebase Stoarage.
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());
}
});
}
});
private void getDownloadUrl(){
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
StorageReference imageRef = storageRef.child("image.jpg");
imageRef.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String profileimageurl =task.getResult().toString();
Log.e("URL",profileimageurl);
ShowPathTextView.setText(profileimageurl);
}
});
}

How to write an Upload firebase method with ProgressBar out of the Activity?

I am using Firebase upload and I want to write the uploaded method in a class out of the activity as I want to use it several times and at the same time I want to use ProgressBar that shows the progress and as it is known we can't use findViewById out of activity or Fragment.
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getError();
float progress = (float) ((100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
System.out.println("Upload is " + progress + "% done");
**Here I wanna use a progressBar**
}
}).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
#Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
System.out.println("Upload is paused");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
int errorCode = ((StorageException) exception).getErrorCode();
String errorMessage = exception.getMessage();
// test the errorCode and errorMessage, and handle accordingly
Log.d(TAG, "onSuccess: The photo has NOT been uploaded" + errorCode + errorMessage);
Toast.makeText(mContext, "Sorry the photo has not been uploaded .. Please Try again", Toast.LENGTH_SHORT);
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
circleProgressBar.setVisibility(View.GONE);
Log.d(TAG, "onSuccess: The photo is being uploaded");
Toast.makeText(mContext, "The photo has been uploaded successfully", Toast.LENGTH_SHORT).show();
//
}
}).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 ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
if (downloadUri != null){
String photoStringUrl = downloadUri.toString();
Log.d(TAG, "onComplete: Upload " + photoStringUrl);
//Inserting the profile photo into database {user_profile_account}
firebaseUtilities.saveProfilePhotoToDatabase(photoStringUrl);
}
}
You can pass Activity as a parameter instead of Context.

How to get imageUrl from firebase storage to store in firebase realtime database?

Basically I have created a class called 'Club'. I save a new club to firebase realtime database successfully with no real problems, until I want to add an imageURL (called clubImage) from Firebase Storage to my club class.
I am able to succesfully upload my image to Firebase Storage using the below code.
private void uploadImage() {
//upload selected image to database
//code from https://code.tutsplus.com/tutorials/image-upload-to-firebase-in-android-application--cms-29934
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(AddClubActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(AddClubActivity.this, "Failed "+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());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
This all works fine. However, in the same method, I also have this code, which is where I try to get my downloadURL for the uploaded image.
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
clubImage = downloadUrl.toString();
}
});
I know it is inefficient to have two OnSuccessListeners for the same thing, I am just not sure how else to go about both uploading an image and getting the downloadUrl at the same time.
Regardless, this doesn't work, and my new club saves without the clubImage field.
I get the error: E/StorageException: StorageException has occurred.
Object does not exist at location.
Does anyone know how to fix this?
Thanks.
I know it is inefficient to have two OnSuccessListeners for the same thing
You have two tasks that you're trying to complete:
Upload a file
Get the download URL for that file
Since these are two separate tasks, you'll need two OnSuccessListeners. There is nothing inefficient about this, nor are the tasks the same.
The Firebase documentation on getting a download URL after uploading shows precisely how to complete these two tasks in succession:
final StorageReference ref = storageRef.child("images/mountains.jpg");
uploadTask = ref.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 ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
} else {
// Handle failures
// ...
}
}
});
You'll note that this code first completes the uploadTask (which uploads the file) and only then starts a new task to get the download URL. Executing the tasks in this sequence prevents the "Object does not exist at location" error message you get.
try using this:
private Uri ImageUri; //and get image from gallery intent to this ImageUri
...............
StorageReference filePath = FirebaseStorage.getInstance().getReference().child("Club Images").child(ImageUri.getLastPathSegment() + ".jpg");
filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task)
{
if(task.isSuccessful())
{
downloadUrl = task.getResult().getDownloadUrl().toString();
updatetoFirebaseDatabase();
}
else
{
String message = task.getException().getMessage();
}
}
});
...........
create updatetoFirebaseDatabase(String imageUrl) method:
updatetoFirebaseDatabase(String imageUrl){
//implement FirebaseDatabase setvalue method with given image URL
}

Unable to get download url from Firebase

I am getting this error when trying to retrieve image from firebase storage.
java.lang.IllegalStateException: Task is not yet complete on upload task.
Code:-
Uri imageUri = data.getData();
final StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(imageUri)
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Toast.makeText(ProfileActivity.this, "Profile Image Uploaded", Toast.LENGTH_SHORT).show();
String downloadUri = filePath.getDownloadUrl().getResult().toString();
UserRef.child("profileImage").setValue(downloadUri).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent selfIntent = new Intent(ProfileActivity.this,ProfileActivity.class);
startActivity(selfIntent);
Toast.makeText(ProfileActivity.this, "Profile image uploaded to database", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
else {
String message = task.getException().getMessage();
Toast.makeText(ProfileActivity.this, "Error Occurred" + message, Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
}
});
filePath.getDownloadUrl() returns a Task that tracks the asynchronous work required to get the url. You can't just call getResult() on it immediately - you have to listen to its results like your are currently with putFile().
Read this for more information: How to get URL from Firebase Storage getDownloadURL

How to get URL from Firebase Storage getDownloadURL

I'm trying to get the "long term persistent download link" to files in our Firebase storage bucket.
I've changed the permissions of this to
service firebase.storage {
match /b/project-xxx.appspot.com/o {
match /{allPaths=**} {
allow read, write;
}
}
}
And my javacode looks like this:
private String niceLink (String date){
String link;
// Points to the root reference
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference dateRef = storageRef.child("/" + date+ ".csv");
link = dateRef.getDownloadUrl().toString();
return link;
}
When I run this I get the uri link that looks something like
com.google.android.gms.tasks.zzh#xxx
Question 1. Can I from this get the download link similar to: https://firebasestorage.googleapis.com/v0/b/project-xxxx.appspot.com/o/20-5-2016.csv?alt=media&token=b5d45a7f-3ab7-4f9b-b661-3a2187adxxxx
When trying to get the link above I changed the last row before my return, like this:
private String niceLink (String date){
String link;
// Points to the root reference
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference dateRef = storageRef.child("/" + date+ ".csv");
link = dateRef.getDownloadUrl().getResult().toString();
return link;
}
But when doing this i get a 403 error, and the app crashing. The consol tells me this is bc user is not logged in /auth.
"Please sign in before asking for token"
Question 2. How do I fix this?
Please refer to the documentation for getting a download URL.
When you call getDownloadUrl(), the call is asynchronous and you must subscribe on a success callback to obtain the results:
// Calls the server to securely obtain an unguessable download Url
private void getUrlAsync (String date){
// Points to the root reference
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference dateRef = storageRef.child("/" + date+ ".csv");
dateRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
#Override
public void onSuccess(Uri downloadUrl)
{
//do something with downloadurl
}
});
}
This will return a public unguessable download url. If you just uploaded a file, this public url will be in the success callback of the upload (you do not need to call another async method after you've uploaded).
However, if all you want is a String representation of the reference, you can just call .toString()
// Returns a Uri of the form gs://bucket/path that can be used
// in future calls to getReferenceFromUrl to perform additional
// actions
private String niceRefLink (String date){
// Points to the root reference
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference dateRef = storageRef.child("/" + date+ ".csv");
return dateRef.toString();
}
//Firebase Storage - Easy to Working with uploads and downloads.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RC_SIGN_IN){
if(resultCode == RESULT_OK){
Toast.makeText(this,"Signed in!", LENGTH_SHORT).show();
} else if(resultCode == RESULT_CANCELED){
Toast.makeText(this,"Signed in canceled!", LENGTH_SHORT).show();
finish();
}
} else if(requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK){
// HERE I CALLED THAT METHOD
uploadPhotoInFirebase(data);
}
}
private void uploadPhotoInFirebase(#Nullable Intent data) {
Uri selectedImageUri = data.getData();
// Get a reference to store file at chat_photos/<FILENAME>
final StorageReference photoRef = mChatPhotoStorageReference
.child(selectedImageUri
.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Download file From Firebase Storage
photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadPhotoUrl) {
//Now play with downloadPhotoUrl
//Store data into Firebase Realtime Database
FriendlyMessage friendlyMessage = new FriendlyMessage
(null, mUsername, downloadPhotoUrl.toString());
mDatabaseReference.push().setValue(friendlyMessage);
}
});
}
});
}
here i am uploading and getting the image url at the same time...
final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");
if (uriProfileImage != null) {
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// profileImageUrl taskSnapshot.getDownloadUrl().toString(); //this is depreciated
//this is the new way to do it
profileImageRef.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String profileImageUrl=task.getResult().toString();
Log.i("URL",profileImageUrl);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(ProfileActivity.this, "aaa "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
For me, I did my code in Kotlin and I had the same error "getDownload()". Here are both the dependencies that worked for me and the Kotlin code.
implementation 'com.google.firebase:firebase-storage:18.1.0' firebase storage dependencies
This what I added and it worked for me in Kotlin. Storage() would come before Download()
profileImageUri = taskSnapshot.storage.downloadUrl.toString()
StorageReference mStorageRef = FirebaseStorage.getInstance().getReference();
final StorageReference fileupload=mStorageRef.child("Photos").child(fileUri.getLastPathSegment());
UploadTask uploadTask = fileupload.putFile(fileUri);
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();
Picasso.get().load(downloadUri.toString()).into(image);
} else {
// Handle failures
}
}
});
Clean And Simple
private void putImageInStorage(StorageReference storageReference, Uri uri, final String key) {
storageReference.putFile(uri).addOnCompleteListener(MainActivity.this,
new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
task.getResult().getMetadata().getReference().getDownloadUrl()
.addOnCompleteListener(MainActivity.this,
new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
FriendlyMessage friendlyMessage =
new FriendlyMessage(null, mUsername, mPhotoUrl,
task.getResult().toString());
mFirebaseDatabaseReference.child(MESSAGES_CHILD).child(key)
.setValue(friendlyMessage);
}
}
});
} else {
Log.w(TAG, "Image upload task was not successful.",
task.getException());
}
}
});
}
The getDownloadUrl method was removed in firebase versions greater than 11.0.5
I recommend using version 11.0.2 that still uses this method.
The getDownloadUrl method has now been depreciated in the new firebase update. Instead use the following method.
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
change the received URI to URL
val urlTask = uploadTask.continueWith { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
spcaeRef.downloadUrl
}.addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUri = task.result
//URL
val url = downloadUri!!.result
} else {
//handle failure here
}
}
You can Upload images to firestore and get it's download URL as below function:
Future<String> uploadPic(File _image) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
var downloadURL = await(await uploadTask.onComplete).ref.getDownloadURL();
var url =downloadURL.toString();
return url;
}
Also you can do as follows In latest Firebase_storage version nullsafe,
//Import
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
Future<void> _downloadLink(firebase_storage.Reference ref) async {
//Getting link make sure call await to make sure this function returned a value
final link = await ref.getDownloadURL();
await Clipboard.setData(ClipboardData(
text: link,
));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Success!\n Copied download URL to Clipboard!',
),
),
);
}
implementation 'com.google.firebase:firebase-storage:19.2.0'
Recently getting url from upload task wasn't working so I tried this and worked for me on above dependency.
So inside where you use firebase upload method use this.
filepath is the reference of Firebase Stoarage.
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());
}
});
}
});
private void getDownloadUrl(){
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
StorageReference imageRef = storageRef.child("image.jpg");
imageRef.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String profileimageurl =task.getResult().toString();
Log.e("URL",profileimageurl);
ShowPathTextView.setText(profileimageurl);
}
});
}

Categories

Resources