Image is not Uploading in Firebase - android

I'm trying to make a chatting app in which I want users to upload images, and I'm using Firebase RealTime Database to store user's data. taskSnapshot.downloadUrl() method is deprecated, as I've used a different approach to upload images to Firebase as shown in documentation
https://firebase.google.com/docs/storage/android/upload-files
and this StackOverflow
post:taskSnapshot.getDownloadUrl() is deprecated
But still, image is not uploading to the database.
And I've also tried things like clean project, rebuild project, Invalidate and Restart.
This is the code I'm using to upload images to Firebase RealTime Database:
// ImagePickerButton shows an image picker to upload an image for a
message
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
and then in onActivityResults method :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
Toast.makeText(MainActivity.this, "Signed-In",
Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "Signed-In Cancel",
Toast.LENGTH_SHORT).show();
finish();
} else if (requestCode == RC_PHOTO_PICKER && resultCode ==
RESULT_OK) {
Uri selectedUri = data.getData();
final StorageReference storageReference = mChatPhotosStorageReference.
child(selectedUri.getLastPathSegment());
UploadTask uploadTask = storageReference.putFile(selectedUri);
Task<Uri> uriTask = 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 storageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUrl = task.getResult();
FriendlyMessage message = new FriendlyMessage(null, mUsername, downloadUrl.toString());
mMessageDatabaseReference.push().setValue(message);
}
}
});
This is the Github link for full project: https://github.com/harshabhadra/FriendlyChat

Use this to upload photo to Firebase Storage in byte
private void uploadImage(byte[] data) {
submitButton.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
final String userId = DatabaseContants.getCurrentUser().getUid();
photo_description_edit_text.setVisibility(View.GONE);
StorageMetadata metadata = new StorageMetadata.Builder()
.setContentType("image/webp")
.build();
final String photoName = System.currentTimeMillis() + "_byUser_" + userId;
StorageReference imageRef = StorageConstants.getImageRef(photoName + ".webp");
UploadTask uploadTask = imageRef.putBytes(data, metadata);
final Resources res = getResources();
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = 100.0 * (taskSnapshot.getBytesTransferred() /
taskSnapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size,
// content-type, and download URL.
Log.d(LOG_TAG, "Image is successfully uploaded: " + taskSnapshot.getMetadata());
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Analytics.registerUpload(activity, userId);
PhotoModel photoModel = new PhotoModel(userId, photoDescription, "none",
0, 0, rotation, photoName + ".webp");
DatabaseContants.getPhotoRef().child(photoName).setValue(photoModel);
Utils.photosUploadedCounter++;
if (Utils.photosUploadedCounter % 2 == 0) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
NotificatonConstants.sendNotification(activity,
res.getString(R.string.failure_title),
res.getString(R.string.failure_message),
NotificatonConstants.UPLOAD_ID);
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
NotificatonConstants.sendNotification(activity,
res.getString(R.string.success_title),
res.getString(R.string.success_message),
NotificatonConstants.UPLOAD_ID);
}
});
}

Related

getDownloadURL isn't inputting the link i need

Trying to get the downloadUrl link and put it into the "profile/imageURL" node on database.
I'm new to firebase and android development, so i was reading through release notes etc on storage and noticed in the notes and found information on downloadUrl. I understand there are plenty of questions on this topic but it's hard to apply it to this code.
"Deprecated the getDownloadUrl() and getDownloadUrls() methods of the StorageMetadata class. Use StorageReference.getDownloadUrl() instead."
But i'm trying to pull the downloadUrl link not from the metadata stored in firebase storage
I can successfully upload the picture to firebase storage but when i put the downloadUrl into firebase DB into the node i want. it inputs "com.google.android.gms.tasks.zzu#xxxxx"
final String downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
UserProfileRef.child("profile").child("imageURL").setValue(downloadUrl)
I have tried the following 2 codes, This code outputs the uri com.google.xxxx
protected void onActivityResult( int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
{
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
if (requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait, while we are uploading image...");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
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())
{
Toast.makeText(ProfileActivity.this, "Profile Image stored Successfully to the the storage...", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
UserProfileRef.child("profile").child("imageURL").setValue(downloadUrl)
.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 stored to firebase database successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(ProfileActivity.this, "Error Occured..." + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
});
}
else
{
Toast.makeText(this, "Error Occured: Image can't be cropped, try again..", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
This second code was tried with the help of other users questions and trying to solve it that way. Although i get an error on .setValue(downloadUrl)
protected void onActivityResult( int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
{
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
if (requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait, while we are uploading image...");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
Uri resultUri = result.getUri();
final StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
}
});
UserProfileRef.child("profile").child("imageURL").setValue(downloadUrl)
.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 stored to firebase database successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(ProfileActivity.this, "Error Occured..." + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
});
}
else
{
Toast.makeText(this, "Error Occured: Image can't be cropped, try again..", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
Calling getDownloadUrl() returns a Task that asynchronously gets the download URL from the server. When it has retrieved the download URL, it calls onComplete/onSuccess. This means the download URL value is only available inside the onComplete/onSuccess method. Any code that needs the download URL needs to be inside onComplete/onSuccess.
So something like:
filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UserProfileRef.child("profile").child("imageURL").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
loadingBar.dismiss();
if(task.isSuccessful()) {
Intent selfIntent = new Intent(ProfileActivity.this, ProfileActivity.class);
startActivity(selfIntent);
Toast.makeText(ProfileActivity.this, "Profile image stored to firebase database successfully.", Toast.LENGTH_SHORT).show();
}
else {
String message = task.getException().getMessage();
Toast.makeText(ProfileActivity.this, "Error Occured..." + message, Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
});
Now having the code inside the onSuccess is of course not going to be very reusable. So you may consider creating a custom callback interface as shown here. But the interface will be quite similar to the Task<Uri> interface in the example above, so I'm not sure it is worth the effort.
For an example of how to still keep the code separate from the onComplete by having your own custom callback interface, see getContactsFromFirebase() method return an empty list.

How to get Firebase Storage image URL in android studio?

I want to display image on imageView from Firebase Storage without saving the picture in the device, so I've tried to use the highlighted URL (from the photo below) and it works but I don't want to write the address manually.
How can I get the address using the code?
p.s I tried dataBaseStorageRef.getDownloadUrl() and it gives me another URL, not the one from the picture.
enter image description here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final StorageReference filePath = storage.child("books").child(""+AddBook.book_id+1).child("photo.jpg");
if(requestCode == RESULT_GALLERY){
if (resultCode == RESULT_OK){
pic_uri = data.getData();
book_img.setImageURI(pic_uri);
filePath.putFile(pic_uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(AddBookActivity.this, "Upload done", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddBookActivity.this, "Failed to upload!", Toast.LENGTH_SHORT).show();
}
});
img_addr = filePath.getDownloadUrl().toString();
Toast.makeText(this, "picture was selected", Toast.LENGTH_SHORT).show();
}
}
}
Then, I'm trying to display the pic from img_addr from another activity
and it doesn't work because the address of image_addr is not good (if I replace manually img_addr to the address from the attached link it works)
if(books_list.get(i).img_addr!=null){
Toast.makeText(v.getContext(),books_list.get(i).img_addr,Toast.LENGTH_LONG).show();
Picasso.with(v.getContext()).load(books_list.get(i).img_addr).resize(50,50).into(img);
}
Thanks to those who help
You can use continueWithTask method to return the download url
Like the following:
final UploadTask uploadTask = filepath.putFile(uri);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
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 filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
thumb_download_url = task.getResult().toString();
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
Make getDownloadUrl() asynchronous by adding onsuccess and onfailure listeners to it.
Your complete image upload task should look like below
photoReference.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
photoReference.getDownloadUrl().addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//do something
}
}).addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//get your image uri here
Uri imgUrl = uri;
String imgStringUrl = imgUrl.toString();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// do something
}
});
You can get download URL from below method:
private void uploadToStorage(String imgPath, String fileName) {
Uri file = Uri.fromFile(new File(imgPath));
StorageReference storageReference = mStorageRef.child(userId + "/images/" + fileName);
storageReference.putFile(file).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getStorage().getDownloadUrl();
downloadUrl.addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
Log.v(TAG, "Media is uploaded");
String downloadURL = "https://" + task.getResult().getEncodedAuthority()
+ task.getResult().getEncodedPath()
+ "?alt=media&token="
+ task.getResult().getQueryParameters("token").get(0);
Log.v(TAG, "downloadURL: " + downloadURL);
//save your downloadURL
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.v(TAG, "Media is not uploaded");
Log.v(TAG, "Exception: " + exception.getLocalizedMessage());
}
});
}
You can also get scheme name & query from methods under task.getResult()

getDownloadUri() in Firebase Storage is deprecated or cannot resolve [duplicate]

To upload images to Firebase Storage I am attaching addOnSuccessListener on the instance of the StorageReference. While overriding onSuccess method I am calling getDownloadUrl() on the instance of taskSnapshot but it is giving me an error saying
Can't resolve method getDownloadUrl()
This app I had created 2 months ago, earlier this app was working fine and getDownloadUrl() was working fine as well. Also, in taskSnapshot instance when I press Ctrl+space, in the suggestions I don't find getDownloadUrl() method. Why is it happening?
Code to onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Signed in!!!1", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Failed to sign in", Toast.LENGTH_SHORT).show();
finish();
}
}
else if(requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK){
Uri selectedPhoto = data.getData();
StorageReference localRefrence = storageReference.child(selectedPhoto.getLastPathSegment());
// Uploading the file on the storage
localRefrence.putFile(selectedPhoto).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
FriendlyMessage message = new FriendlyMessage(mUsername, null, downloadUrl.toString());
databaseReference.push().setValue(message);
}
});
}
}
The Firebase API has changed.
May 23, 2018
Cloud Storage version 16.0.1
Removed the deprecated StorageMetadata.getDownloadUrl() and UploadTask.TaskSnapshot.getDownloadUrl() methods. To get a current download URL, use StorageReference.getDownloadUr().
UploadTask.TaskSnapshot has a method named getMetadata() which returns a StorageMetadata object.
This StorageMetadata object contains a method named getReference() which returns a StorageReference object.
That StorageReference object contains the getDownloadUrl() method, which now returns a Task object instead of an Uri object.
This Task must then be listened upon in order to obtain the Uri, which can be done asynchronously or in a blocking manner; see the Tasks API for that.
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
// ...
}
}
});
final StorageReference filePath = mImageStore.child("profile_images").child("full_image").child(userId + ".jpg");
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Bitmap hochladen
uploadBitMap(uri.toString());
}
});
The .getDownloadURL is no longer available and deprecated.
from the documentation Task<Uri> and getdownloadUrl();
Asynchronously retrieves a long lived download URL with a revokable token.
see documentation
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
//continue with your code
The getDownloadUrl method has been depreceated. Instead use the following
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
You should try this one. Understand it and try to implement in yours
buttonSetup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editText_name.getText().toString();
if (!TextUtils.isEmpty(name) && mainImageURI != null) {
final String user_id = firebaseAuth.getCurrentUser().getUid();
progressBar_setup.setVisibility(View.VISIBLE);
final StorageReference image_path = storageReference.child("profile_images").child(user_id + ".jpg");
UploadTask uploadTask = image_path.putFile(mainImageURI);
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 image_path.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
Uri downloadUrl = task.getResult();
Log.i("The URL : ", downloadUrl.toString());
}
}
});
}
}
});
Try
{
firebase.storage()
.child()
.getDownloadURL().then()
}

Firebase Storage getDownloadUrl() method can't be resolved

To upload images to Firebase Storage I am attaching addOnSuccessListener on the instance of the StorageReference. While overriding onSuccess method I am calling getDownloadUrl() on the instance of taskSnapshot but it is giving me an error saying
Can't resolve method getDownloadUrl()
This app I had created 2 months ago, earlier this app was working fine and getDownloadUrl() was working fine as well. Also, in taskSnapshot instance when I press Ctrl+space, in the suggestions I don't find getDownloadUrl() method. Why is it happening?
Code to onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Signed in!!!1", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Failed to sign in", Toast.LENGTH_SHORT).show();
finish();
}
}
else if(requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK){
Uri selectedPhoto = data.getData();
StorageReference localRefrence = storageReference.child(selectedPhoto.getLastPathSegment());
// Uploading the file on the storage
localRefrence.putFile(selectedPhoto).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
FriendlyMessage message = new FriendlyMessage(mUsername, null, downloadUrl.toString());
databaseReference.push().setValue(message);
}
});
}
}
The Firebase API has changed.
May 23, 2018
Cloud Storage version 16.0.1
Removed the deprecated StorageMetadata.getDownloadUrl() and UploadTask.TaskSnapshot.getDownloadUrl() methods. To get a current download URL, use StorageReference.getDownloadUr().
UploadTask.TaskSnapshot has a method named getMetadata() which returns a StorageMetadata object.
This StorageMetadata object contains a method named getReference() which returns a StorageReference object.
That StorageReference object contains the getDownloadUrl() method, which now returns a Task object instead of an Uri object.
This Task must then be listened upon in order to obtain the Uri, which can be done asynchronously or in a blocking manner; see the Tasks API for that.
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
// ...
}
}
});
final StorageReference filePath = mImageStore.child("profile_images").child("full_image").child(userId + ".jpg");
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Bitmap hochladen
uploadBitMap(uri.toString());
}
});
The .getDownloadURL is no longer available and deprecated.
from the documentation Task<Uri> and getdownloadUrl();
Asynchronously retrieves a long lived download URL with a revokable token.
see documentation
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
//continue with your code
The getDownloadUrl method has been depreceated. Instead use the following
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
You should try this one. Understand it and try to implement in yours
buttonSetup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editText_name.getText().toString();
if (!TextUtils.isEmpty(name) && mainImageURI != null) {
final String user_id = firebaseAuth.getCurrentUser().getUid();
progressBar_setup.setVisibility(View.VISIBLE);
final StorageReference image_path = storageReference.child("profile_images").child(user_id + ".jpg");
UploadTask uploadTask = image_path.putFile(mainImageURI);
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 image_path.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
Uri downloadUrl = task.getResult();
Log.i("The URL : ", downloadUrl.toString());
}
}
});
}
}
});
Try
{
firebase.storage()
.child()
.getDownloadURL().then()
}

FireBase Storage Image Upload Android

I have created an app running with Firebase Storage. The idea is that you select an Image from your Photo Gallery and then Upload it to Firebase Storage. The connection with Firebase seems to work fine, I can select an Image. The problem arises when I push the Submit Button to upload it to Firebase.
When I click it one time, nothing happens.
When I click it a few times, I get the message "an unknown error occurred, please check the HTTP result code and inner exception"..
What should I do, looking for advice..
From the Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
From the Activity:
public class PostActivity extends AppCompatActivity {
private static final int GALLERY_REQUEST = 2;
private Uri uri = null;
private ImageButton imageButton;
private EditText editName;
private EditText editDescription;
private StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
//reference the two edittext Views, initialize them
editName = (EditText) findViewById(R.id.editName);
editDescription = (EditText) findViewById(R.id.editDescription);
//add the reference to the storagereference, initialize it
storageReference = FirebaseStorage.getInstance().getReference();
}
public void ImageButtonClicked (View view){
Intent galleryintent = new Intent (Intent.ACTION_GET_CONTENT);
galleryintent.setType("Image/*");
startActivityForResult(galleryintent, GALLERY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
uri = data.getData();
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setImageURI(uri);
}
}
public void submitButtonClicked (View view){
String titleValue = editName.getText().toString().trim();
String titleDescription = editDescription.getText().toString().trim();
if (!TextUtils.isEmpty(titleValue) && !TextUtils.isEmpty(titleDescription)){
StorageReference filePath = storageReference.child("PostImage").child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadurl = taskSnapshot.getDownloadUrl();
Toast.makeText(PostActivity.this,"uploadcomplete",Toast.LENGTH_LONG).show();
}
});
filePath.putFile(uri).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
Try this method for image upload to firebase storage:
private void uploadMethod() {
progressDialog();
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
StorageReference storageReferenceProfilePic = firebaseStorage.getReference();
StorageReference imageRef = storageReferenceProfilePic.child("Your Path" + "/" + "Image Name" + ".jpg");
imageRef.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//if the upload is successful
//hiding the progress dialog
//and displaying a success toast
dismissDialog();
String profilePicUrl = taskSnapshot.getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
//if the upload is not successful
//hiding the progress dialog
dismissDialog();
//and displaying error message
Toast.makeText(getActivity(), exception.getCause().getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//calculating progress percentage
// double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
// //displaying percentage in progress dialog
// progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
}
I have found an answer through the code of Rahul Chandrabhan.
What I have changed is to remove the last part of the following method:
StorageReference filePath =
storageReference.child("PostImage").child(uri.getLastPathSegment());
TO
StorageReference filePath = storageReference.child("PostImage");
To perform image upload on firebase use below method:
void uploadFile(String pathToFile, String fileName, String serverFolder, String contentType) {
if (pathToFile != null && !pathToFile.isEmpty()) {
File file = new File(pathToFile);
if (file.exists()) {
Uri uri = Uri.fromFile(new File(pathToFile));
// Create a storage reference from our app
mStorageRef = mFirebaseStorage.getReference();
// Create a reference to "mountains.jpg"
//StorageReference mountainsRef = storageRef.child(fileName);
// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef = mStorageRef.child(serverFolder+"/" + fileName);
StorageMetadata metadata = null;
if (contentType != null && !contentType.isEmpty()) {
// Create file metadata including the content type
metadata = new StorageMetadata.Builder()
.setContentType(contentType)
.build();
}
if (metadata != null) {
uploadFileTask = mountainImagesRef.putFile(uri, metadata);
} else {
uploadFileTask = mountainImagesRef.putFile(uri);
}
uploadFileTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
hideProgressDialog();
exception.printStackTrace();
Log.e(TAG,exception.getMessage());
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadFailure(exception.getMessage());
}
}
});
uploadFileTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
hideProgressDialog();
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Log.e(TAG, "Upload is success "+ downloadUrl);
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadSuccess("Upload is success "+ downloadUrl.toString(), downloadUrl.toString());
}
}
});
// Observe state change events such as progress, pause, and resume
uploadFileTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
hideProgressDialog();
double progressPercent = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressPercent = Double.parseDouble(FirebaseUtil.formatDecimal(progressPercent,2));
Log.e(TAG, "File Upload is " + progressPercent + "% done");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadProgress(progressPercent);
}
}
});
uploadFileTask.addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
#Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
hideProgressDialog();
Log.e(TAG, "Upload is paused");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadPaused("Upload is paused");
}
}
});
}
else
{
hideProgressDialog();
Log.e(TAG, "Upload file does not exists");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadFailure("Upload file does not exists");
}
}
}else
{
hideProgressDialog();
Log.e(TAG,"pathToFile cannot be null or empty");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadFailure("pathToFile cannot be null or empty");
}
}
}
Make a call this method as below:
public void uploadDummyPicture(String email, String imagePath){
if (imagePath == null) {
return;
}
if (!isValidEmail(email)) {
return;
}
String serverFolder = "dummy_images/" + email; //path of your choice on firebase storage server
String fileName = "DummyPhoto.png";
uploadFile(imagePath, fileName, serverFolder, "image/png");
showProgressDialog();
}
Make sure to check the firebase storage rules before using above code as explained here. If the rules have firebase authentication required, then first complete firebase authentication of the current user and then start uploading the file.
I hope this answer will you solve your problem.
In my case, the URI which I was fetching on the onActivityResult function was just not in the right format.
Previously I was parsing like this
uri=Uri.parse(your image path)
but after changing to this it worked
uri=Uri.fromFile(new File(your image path))
the upload function
public void upload()
{
if(uri!=null)
{
progressBar.setVisibility(View.VISIBLE);
progressBar_tv.setVisibility(View.VISIBLE);
Log.i("URI",uri.getPath());
UploadTask uploadTask=sRef.putFile(uri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(VideoEditAndUploadActivity.this, "Upload Failed:"+e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();;
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(VideoEditAndUploadActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
progressBar_tv.setVisibility(View.INVISIBLE);
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
updateUploadProgress(snapshot);
}
});
}
else{
Toast.makeText(this, "Video Uri is null: please choose a video first!", Toast.LENGTH_SHORT).show();
}
}
the update progress bar function
#SuppressLint("DefaultLocale")
private void updateUploadProgress(UploadTask.TaskSnapshot snapshot) {
long fileSize=snapshot.getTotalByteCount();
long uploadBytes=snapshot.getBytesTransferred();
long progress=(100*uploadBytes)/fileSize;
progressBar.setProgress((int) progress);
progressBar_tv.setText(String.format("%d%%", progress));
}
If you are using rxjava then you could use the following snippet
public Observable<FirebaseFile> uploadImageToFirebase(#NonNull Uri file) {
return Observable.create(emitter -> {
try {
final StorageReference conversationReference = reference.child("some-identifier");
final File localFile = new File(file.getPath());
final StorageReference fileReference = conversationReference
.child(UUID.randomUUID().toString().toLowerCase(Locale.ROOT) + "-" + localFile.getName());
final UploadTask uploadTask = fileReference.putFile(file);
uploadTask.continueWithTask(task -> {
if (task.isSuccessful()) {
return fileReference.getDownloadUrl();
} else {
if (task.getException() != null) {
throw task.getException();
} else {
throw new RuntimeException("Error uploading file to firebase storage");
}
}
}).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
final Uri downloadUri = task.getResult();
if (downloadUri != null) {
emitter.onNext(new FirebaseFile(file.getPath(), downloadUri.toString(), 100));
emitter.onComplete();
} else {
if (!emitter.isDisposed()) {
emitter.onError(new RuntimeException("Error uploading stream to firebase storage"));
}
}
} else {
if (!emitter.isDisposed()) {
emitter.onError(new RuntimeException("Error uploading file to firebase storage"));
}
}
});
uploadTask.addOnProgressListener(taskSnapshot -> {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
emitter.onNext(new FirebaseFile(file.getPath(), null, (int) progress));
});
} catch (Exception e) {
if (!emitter.isDisposed()) {
emitter.onError(e);
}
}
});
}
Where
FirebaseStorage fs = FirebaseStorage.getInstance()
and
StorageReference StorageReference = firebaseStorage.getReference("some-identifier-if-any");```

Categories

Resources