getDownloadURL isn't inputting the link i need - android

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.

Related

How Can I add My Captured Image to My Hashmap

I am still learning hashmaps and database structures so please forgive me if this is a basic question. I've tried to research but nothing seems to work. I have a method in the same activity where I capture an image which is pushed to Firebase Storage. The image successfully goes to Firebase Storage, but I cannot figure out how to add the image to my hashmap to go to the Firebase Database. My hashmap is below and currently works.
Thank you for your help.
String title = title_edit_text.getText().toString();
String first_name = firstname.getText().toString();
String last_name = lastname.getText().toString();
if (TextUtils.isEmpty(title)) {
title_edit_text.setError("Input is required!");
} else {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
String creation_date= dateFormat.format(date);
DateFormat date_format_for_time = new SimpleDateFormat("hh:mm:ss a");
Date time = new Date();
String creation_time= date_format_for_time.format(time);
HashMap userMap = new HashMap();
userMap.put("title", title);
userMap.put("creation_date", creation_date);
userMap.put("creation_time", creation_time);
userMap.put("first_name", first_name);
userMap.put("last_name", last_name);
String upload = UsersReference2.push().getKey();
UsersReference2.child(upload).setValue(userMap).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
sendBackActivity();
Toast.makeText(Adding_Activity.this, "Successfully Save.", Toast.LENGTH_LONG).show();
} else {
String message = task.getException().getMessage();
Toast.makeText(AddingActivity.this, "Error. Did Not Save: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) {
image_uri = data.getData();
CropImage.activity(image_uri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(3, 2)
.start(this);
}
// when pressing the crop button//
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
StorageReference filePath = CoverPostReference.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(Adding_Activity.this, "Image has been added sucessfully...", Toast.LENGTH_SHORT).show();
Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UsersReference2.child("cover_image").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(Adding_Activity.this, "Image has been stored...", Toast.LENGTH_SHORT).show();
} else {
String message = task.getException().getMessage();
Toast.makeText(Adding_Activity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
});
} else {
Toast.makeText(Adding_Activity.this, "Error: Image did not upload. Please try again.", Toast.LENGTH_SHORT).show();
}
}
}
You shouldn't/wouldn't store the image bitmap data into the hashmap, instead you should store the location to the bitmap (URI) to the hashmap (and database) and then use that to access the image.
Storing
Map<String, Uri> bitmapUriMap = new HashMap<String,Uri>();
bitmapUriMap.put("MyLocalBitmapName", UriOfBitmap);
Accessing
Then when you have the URI you just decode it
Uri uri = bitmapUriMap.get("MyLocalBitmapName);
Bitmap decodedUri = BitmapFactory.decodeFile(new File(uri.getPath()));
This is what you would store in the database. For instance if you want the image of a user, then you would store the image uri within your firebase database and then you would access it this way. Storing a bitmap in a database is not ideal and not recommended.

Retrieve Image from Firebase using Picasso

I am trying to display my image that stores successfully in Firebase. But whenever I try and display the image it returns a blank image and not the image stored. I think that the image name is wrong when being stored in Firebase. I also did research to try use Glide in my code but don't know how to implement it. I am using the latest dependencies for Firebase.
Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
userName.setVisibility(View.INVISIBLE);
UpdateAccountSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GalleryPick);
}
});
}
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setUserStatus = userStatus.getText().toString();
if (TextUtils.isEmpty(setUserName)) {
Toast.makeText(this, "Please write your user name first....", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setUserStatus)) {
Toast.makeText(this, "Please write your status....", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, String> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUserName);
profileMap.put("status", setUserStatus);
profileMap.put("image", photoUrl);
RootRef.child("Users").child(currentUserID).setValue(profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updated successfully", Toast.LENGTH_SHORT).show();
} else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(currentUserID)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image")))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveUserStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
photoUrl = retrieveProfileImage;
userName.setText(retrieveUserName);
userStatus.setText(retrieveUserStatus);
//Picasso.get().load(retrieveProfileImage).into(userProfileImage);
Picasso.get().load(retrieveProfileImage).resize(100,100).centerCrop().into(userProfileImage);
//Glide.with(SettingsActivity.this).load(retrieveProfileImage).into(userProfileImage);
}
else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveUserStatus = dataSnapshot.child("status").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveUserStatus);
}
else {
userName.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Please set & update your profile information...", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void InitializeFields() {
UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
userName = (EditText) findViewById(R.id.set_user_name);
userStatus = (EditText) findViewById(R.id.set_profile_status);
userProfileImage = (CircleImageView) findViewById(R.id.set_profile_image);
loadingBar = new ProgressDialog(this);
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SettingsActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null) {
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(SettingsActivity.this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Please wait, your profile image is updating...");
loadingBar.setCanceledOnTouchOutside(false);
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(SettingsActivity.this, "Profile Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
final String downloadedUrl = task.getResult().getStorage().getDownloadUrl().toString();
RootRef.child("Users").child(currentUserID).child("image")
.setValue(downloadedUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SettingsActivity.this, "Image saved in Database Successfully...", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
//Glide.with(SettingsActivity.this).load(downloadedUrl).into(userProfileImage);
}
else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
}
Realtime Database before
Realtime Database before - Watch User Warren
Realtime Database after
Realtime Database after - Watch User Warren
Storage before
Storage before adding image
Storage after
Storage after image added

Image is not Uploading in Firebase

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);
}
});
}

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()
}

Categories

Resources