Unable to get URI from storage reference on Firebase - android

I'm trying to get an image URI that is stored in Firebase storage, in order to process it using another method.
I'm using the following:
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl(this.getString(R.string.storage_path));
Uri uri = storageRef.child("groups/pizza.png").getDownloadUrl().getResult();
and getting an error "java.lang.IllegalStateException: Task is not yet complete"

You can get the download URL for a file with:
storageRef.child("groups/pizza.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// TODO: handle uri
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
See the Firebase documentation for downloading data via a URL.

Related

I can't get image url from Firebase using .getDownloadUrl, in my database I have this ""com.google.android.gms.tasks.zzu#e2b2b97" instead of the link [duplicate]

Uri downloaduri=taskSnapshot.getDownloadUrl();//here i cant use getdownloadurl() function
DatabaseReference new_prod=db.push();
new_prod.child("product name").setValue(prod_name);
new_prod.child("product price").setValue(prod_price);
new_prod.child("available stock").setValue(prod_quan);
new_prod.child("product image").setValue(downloaduri);
pd.dismiss();//fragments code
I was unable to use getdownloadurl .I have already stored image in the firebase storage.Is it the fragment that is restricting the use of getdownloadurl? My motive is to make a query to store in firebase.please help me.
The taskSnapshot.getDownloadUrl() method was removed in recent versions of the Firebase Storage SDK. You will need to instead get the download URL from the StorageReference now.
Calling StorageReference.getDownloadUrl() returns a Task, since it needs to retrieve the download URL from the server. So you'll need a completion listener to get the actual URL.
From the documentation on downloading a file:
storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'users/me/profile.png' in uri
System.out.println(uri.toString());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
Alternatively that first line could be this if you're getting the download URL right after uploading (as in your case):
taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
Also see:
Firebase Storage getDownloadUrl() method can't be resolved
Error: cannot find symbol method getDownloadUrl() of type com.google.firebase.storage.UploadTask.TaskSnapshot
The example in the Firebase documentation on uploading a file and getting its download URL
This worked for me after hours of research and differents ways :
filepath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//here
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
final String sdownload_url = String.valueOf(downloadUrl);
storageReference.child("YOUR_CHILD")
.putFile("FILE")
.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot
.getStorage()
.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Uri uri) {
//Put your result here
}
});
}
Below method worked for me.
_fbs_upload_success_listener = new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot _param1) {
Task<Uri> urlTask = _param1.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
String _downloadUrl = downloadUrl.toString();
};
This is Kotlin Solution which worked for me after searching for 3 hrs
val uploadTask =
FirebaseStorage.getInstance().reference.child("images").child(imageName).putBytes(data)
uploadTask.addOnFailureListener {
// Handle unsuccessful uploads
Toast.makeText(baseContext, "Failed to upload", Toast.LENGTH_LONG).show()
}.addOnSuccessListener {
Toast.makeText(
baseContext, "Image uploaded",
Toast.LENGTH_LONG
).show()
var downloadUrl: Uri? = null
FirebaseStorage.getInstance().reference.child("images")
.child(imageName).downloadUrl.addOnSuccessListener { it1 ->
downloadUrl = it1
}
}
downloadUrl is your URL

How can I save the URL of an image with Firebase in Android Studio [duplicate]

Uri downloaduri=taskSnapshot.getDownloadUrl();//here i cant use getdownloadurl() function
DatabaseReference new_prod=db.push();
new_prod.child("product name").setValue(prod_name);
new_prod.child("product price").setValue(prod_price);
new_prod.child("available stock").setValue(prod_quan);
new_prod.child("product image").setValue(downloaduri);
pd.dismiss();//fragments code
I was unable to use getdownloadurl .I have already stored image in the firebase storage.Is it the fragment that is restricting the use of getdownloadurl? My motive is to make a query to store in firebase.please help me.
The taskSnapshot.getDownloadUrl() method was removed in recent versions of the Firebase Storage SDK. You will need to instead get the download URL from the StorageReference now.
Calling StorageReference.getDownloadUrl() returns a Task, since it needs to retrieve the download URL from the server. So you'll need a completion listener to get the actual URL.
From the documentation on downloading a file:
storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'users/me/profile.png' in uri
System.out.println(uri.toString());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
Alternatively that first line could be this if you're getting the download URL right after uploading (as in your case):
taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
Also see:
Firebase Storage getDownloadUrl() method can't be resolved
Error: cannot find symbol method getDownloadUrl() of type com.google.firebase.storage.UploadTask.TaskSnapshot
The example in the Firebase documentation on uploading a file and getting its download URL
This worked for me after hours of research and differents ways :
filepath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//here
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
final String sdownload_url = String.valueOf(downloadUrl);
storageReference.child("YOUR_CHILD")
.putFile("FILE")
.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot
.getStorage()
.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Uri uri) {
//Put your result here
}
});
}
Below method worked for me.
_fbs_upload_success_listener = new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot _param1) {
Task<Uri> urlTask = _param1.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
String _downloadUrl = downloadUrl.toString();
};
This is Kotlin Solution which worked for me after searching for 3 hrs
val uploadTask =
FirebaseStorage.getInstance().reference.child("images").child(imageName).putBytes(data)
uploadTask.addOnFailureListener {
// Handle unsuccessful uploads
Toast.makeText(baseContext, "Failed to upload", Toast.LENGTH_LONG).show()
}.addOnSuccessListener {
Toast.makeText(
baseContext, "Image uploaded",
Toast.LENGTH_LONG
).show()
var downloadUrl: Uri? = null
FirebaseStorage.getInstance().reference.child("images")
.child(imageName).downloadUrl.addOnSuccessListener { it1 ->
downloadUrl = it1
}
}
downloadUrl is your URL

Can't get actual download Url of an image uploaded in firebase storage [duplicate]

This question already has answers here:
How to get URL from Firebase Storage getDownloadURL
(13 answers)
Closed 2 years ago.
I'm trying to get the download url of the image uploaded to firebase database. But Task Uri imageURL = storageReference.getDownloadUrl(); doesn't gives the actual download URL of an image stored in the firebase storage i.e it gives this - com.google.android.gms.tasks.zzu#27da5837
getdownloadUrl() doesn't work in case of as it is deprecated:
Uri imageUrl = storagereference.getdownloadUrl(); //Gives error
please see the code here:
final StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("images").child(imageName);
final UploadTask uploadTask = storageReference.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(CreateSnapActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
//Task<Uri> imageURL = storageReference.getDownloadUrl();
//Log.i("URL", imageURL.toString()); // gives this url - com.google.android.gms.tasks.zzu#27da5837 which is not correct
Task<Uri> urlTask = storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.i("Url", String.valueOf(uri));
imageUrl = uri.toString(); //Gives the correct url but it cannot store this uri value outside this function i.e for Intent shown below outside this func.
}
});
Toast.makeText(CreateSnapActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(CreateSnapActivity.this, ChooseUserActivity.class);
intent.putExtra("imageName", imageName);
intent.putExtra("imageURL", imageUrl);
intent.putExtra("message", captionEditText.getText().toString());
startActivity(intent);
}
});
Calling getDownloadUrl() starts an asynchronous operation, which may take some time to complete. Because of this, your main code continues to run while the download URL is being retrieved to prevent blocking the user. Then when the download URL is available, your onSuccess gets called. Because of this, by the time your intent.putExtra("imageURL", imageUrl) now runs, the imageUrl = uri.toString() hasn't run yet.
To see that this indeed true, I recommend putting some logging in the code to just show the flow, or running it in a debugger and setting breakpoints on the lines I indicated above.
To fix it, any code that needs the download URL, needs to be inside the onSuccess, or be called from there. This applies not just here, but to all code that runs asynchronously, which includes most modern cloud APIs. So I recommend spending some time now studying this behavior, so that you're more comfortable with it going forward.
In your code:
final StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("images").child(imageName);
final UploadTask uploadTask = storageReference.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(CreateSnapActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTask = storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
imageUrl = uri.toString();
Toast.makeText(CreateSnapActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(CreateSnapActivity.this, ChooseUserActivity.class);
intent.putExtra("imageName", imageName);
intent.putExtra("imageURL", imageUrl);
intent.putExtra("message", captionEditText.getText().toString());
startActivity(intent);
}
});
}
});
Also see:
URL generated by Firebase Storage does not allow access to the file
How to get download url for firebase storage and update firestore document?
imageURL is a task.You are trying to print a task. not task's result. please try this code:
Task<Uri> imageURL = storageReference.getDownloadUrl();
Log.i("URL", imageURL.toString());
Log.i("URL", imageURL.result.toString());

How to use getdownloadurl in recent versions?

Uri downloaduri=taskSnapshot.getDownloadUrl();//here i cant use getdownloadurl() function
DatabaseReference new_prod=db.push();
new_prod.child("product name").setValue(prod_name);
new_prod.child("product price").setValue(prod_price);
new_prod.child("available stock").setValue(prod_quan);
new_prod.child("product image").setValue(downloaduri);
pd.dismiss();//fragments code
I was unable to use getdownloadurl .I have already stored image in the firebase storage.Is it the fragment that is restricting the use of getdownloadurl? My motive is to make a query to store in firebase.please help me.
The taskSnapshot.getDownloadUrl() method was removed in recent versions of the Firebase Storage SDK. You will need to instead get the download URL from the StorageReference now.
Calling StorageReference.getDownloadUrl() returns a Task, since it needs to retrieve the download URL from the server. So you'll need a completion listener to get the actual URL.
From the documentation on downloading a file:
storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'users/me/profile.png' in uri
System.out.println(uri.toString());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
Alternatively that first line could be this if you're getting the download URL right after uploading (as in your case):
taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
Also see:
Firebase Storage getDownloadUrl() method can't be resolved
Error: cannot find symbol method getDownloadUrl() of type com.google.firebase.storage.UploadTask.TaskSnapshot
The example in the Firebase documentation on uploading a file and getting its download URL
This worked for me after hours of research and differents ways :
filepath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//here
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
final String sdownload_url = String.valueOf(downloadUrl);
storageReference.child("YOUR_CHILD")
.putFile("FILE")
.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot
.getStorage()
.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Uri uri) {
//Put your result here
}
});
}
Below method worked for me.
_fbs_upload_success_listener = new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot _param1) {
Task<Uri> urlTask = _param1.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
String _downloadUrl = downloadUrl.toString();
};
This is Kotlin Solution which worked for me after searching for 3 hrs
val uploadTask =
FirebaseStorage.getInstance().reference.child("images").child(imageName).putBytes(data)
uploadTask.addOnFailureListener {
// Handle unsuccessful uploads
Toast.makeText(baseContext, "Failed to upload", Toast.LENGTH_LONG).show()
}.addOnSuccessListener {
Toast.makeText(
baseContext, "Image uploaded",
Toast.LENGTH_LONG
).show()
var downloadUrl: Uri? = null
FirebaseStorage.getInstance().reference.child("images")
.child(imageName).downloadUrl.addOnSuccessListener { it1 ->
downloadUrl = it1
}
}
downloadUrl is your URL

Android - Firebase - TaskSnapshot - Method should only be accessed within private scope

I have the following code snippet in my onSuccessListener() to save the download URL of the file I uploaded.
DatabaseReference downloadURLRef = rootRef.child("Child").child(value);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
downloadURLRef.setValue(downloadUrl);
I get this error:
Error TaskSnapshot - Method should only be accessed within private scope while using android studio 2.3.
When I followed this post and suppressed the warning, my app crashes on upload, and the upload fails. Here's the error for that.
What gives? This is straight from the Firebase documentation too.
EDIT: Upload code.
storage = FirebaseStorage.getInstance();
storageRef = storage.getReference(date + "/" + filename);
uploadTask = storageRef.putFile(Uri.fromFile(file));
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// TODO: Fix this bullshit
DatabaseReference downloadURLRef = rootRef.child("Child").child(value);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
downloadURLRef.setValue(downloadUrl);
}
});
Save downloadUrl as a string, not a Uri object:
DatabaseReference downloadURLRef = rootRef.child("Child").child(value);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
downloadURLRef.setValue(downloadUrl.toString()); // <= CHANGE

Categories

Resources