Cant Retrieve Firabase Storage image URL - android

In my app user can upload their image in Firebase storage and database via my app, but i cant retrieve URL of uploaded image to set their profile Image
private FirebaseAuth mAuth;
private DatabaseReference databaseReference;
private StorageReference UserProfileImageRef;
String currentUserID;
databaseReference=FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
UserProfileImageRef=FirebaseStorage.getInstance().getReference().child("Profile Images");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{
String q=UserProfileImageRef.getDownloadUrl().toString();
Toast.makeText(SetupActivity.this, "url"+q, Toast.LENGTH_SHORT).show();
Glide.with(SetupActivity.this)
.load(q)
.into(ProfileImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
enter image description hereenter code here

databaseReference=FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID).child("profileimage");
You forgot to add the child "profileimage"
UPDATE:
Your download url is not same as in the Firebase Storage. I assumed you take the wrong download url.
Refer to this link: https://stackoverflow.com/a/50572357/9346054
filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.d(TAG, "onSuccess: uri= "+ uri.toString());
//You store the download in database.
//set value databaseReference=FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID).child("profileimage").setValue(uri.toString()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
//Success store the link in the database.
Toast.makeText( getApplicationContext(), "Success",Toast.LENGTH_SHORT ).show();
}
}
});
}
});
}
});
UPDATE BASE ON UR ANSWER:
try this one
Uri resulturi = result.getUri();
final 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()) {
//Okay part ni dia ambik link kat firebase storage akan pergi ke photoUri kat student tuu
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Update in database
databaseReference.child("profileimage").setValue(String.valueOf(uri));
Toast.makeText(SetupActivity.this, "successfully", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
});

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())
{
Intent selfIntent=new Intent(SetupActivity.this,SetupActivity.class);
startActivity(selfIntent);
Toast.makeText(SetupActivity.this, "success", Toast.LENGTH_SHORT).show();
final String downloadurl =task.getResult().getStorage().getDownloadUrl().toString();
databaseReference.child("profileimage").setValue(downloadurl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(SetupActivity.this, "successfully", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
else
{
String message=task.getException().getMessage();
Toast.makeText(SetupActivity.this, "error"+message, Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
}
});
}

Related

Update and Delete documents from two different collections on single click

I'm creating an app like olx, Where if you upload ad , its gets posted in two different collections, namly "My Ads" where ads of every logged in user are posted against his ID, and Explore collection Where ads are posted for all users. So if i want to update or delete ad, It should be deleted from both collections! Image Url :https://imgur.com/a/HCKfGBb
String uid= user.getUid();
SellingDetails.put("uid",uid);
final CollectionReference reference = exploreAdDB.collection("cities/" + city + "/" + category);
final CollectionReference myAdDocRef = myAdDB.collection("users/ads/"+uid);
if (imageUri != null) {
final StorageReference fileReference = mStorage.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
UploadTask uploadTask = fileReference.putFile(imageUri);
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
if(downloadUri!=null)
SellingDetails.put("imageUrl",downloadUri.toString());
reference.add(SellingDetails).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(GetLocationActivity.this, "Service Uploaded in explore db ", Toast.LENGTH_SHORT).show();
pgAd.setVisibility(View.INVISIBLE);
Intent intent = new Intent(GetLocationActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
Toast.makeText(GetLocationActivity.this, "Ad posted Successfully", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(GetLocationActivity.this, "Failed adding data into explore db", Toast.LENGTH_SHORT).show();
pgAd.setVisibility(View.INVISIBLE);
}
});
myAdDocRef.add(SellingDetails).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(GetLocationActivity.this, "Data Also added to myAds db", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(GetLocationActivity.this, "Data not added into my ads", Toast.LENGTH_SHORT).show();
}
});
} else {
// Handle failures
Toast.makeText(GetLocationActivity.this, "Failed adding data", Toast.LENGTH_SHORT).show();
}
}
});
}

Wrong download URL retrieved in firebase storage [duplicate]

This question already has answers here:
How to get URL from Firebase Storage getDownloadURL
(13 answers)
How to get the download url from Firebase Storage?
(1 answer)
Closed 3 years ago.
I am retrieving the download URL from a song file that is stored in firebase storage.The URL that i am getting is not the same URL that is in the firebase storage.
Here is the wrong link i get: com.google.android.gms.tasks.zzu#75f559a
Here is the correct link: https://firebasestorage.googleapis.com/v0/b/fouronesixsound-51999.appspot.com/o/Uploads%2F1221?alt=media&token=56beacd5-9abd-4a74-b294-69eb111fcb00
Here is a link to a picture of my database setup:
https://imgur.com/a/Gtl1ThZ
This is my code:
final String fileName = songUri.getLastPathSegment() + "";
//final String fileName1=songUri.getLastPathSegment()+"";
final StorageReference storageRef = storage.getReference();
storageRef.child("Uploads").child(fileName).putFile(songUri)
.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String url =
storageRef.child("Uploads").child(fileName).getDownloadUrl().toString();
//returns the url of the uploaded file
DatabaseReference reference = database.getReference();
reference.child("Uploads").child(fileName).setValue(url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
Toast.makeText(Upload.this, "File Uploaded Successfully", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Upload.this, "Upload failed", Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Upload.this, "Upload failed",Toast.LENGTH_SHORT).show();
}
storageRef.child("Uploads").child(fileName).getDownloadUrl(); returns a Task object, not Uri directly. You have to add completion listener to this task and then upload the url to your database.
final String fileName = songUri.getLastPathSegment() + "";
//final String fileName1=songUri.getLastPathSegment()+"";
final StorageReference storageRef = storage.getReference();
storageRef.child("Uploads").child(fileName).putFile(songUri)
.addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageRef.child("Uploads").child(fileName).getDownloadUrl()
.addOnCompleteListener(new OnCompleteListener < Uri > () {
#Override
public void onComplete(#NonNull Task < Uri > task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
reference.child("Uploads").child(fileName).setValue(downloadUri.toString()).addOnCompleteListener(new OnCompleteListener < Void > () {
#Override
public void onComplete(#NonNull Task < Void > task) {
if (task.isSuccessful())
Toast.makeText(Upload.this, "File Uploaded Successfully", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Upload.this, "Upload failed", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(Upload.this, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Upload.this, "Upload failed", Toast.LENGTH_SHORT).show();
}

How to resolve method getDownloadUrl() [duplicate]

This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
Closed 4 years ago.
Uri resultUri = result.getUri();
String current_user_id= mCurrentUser.getUid();
StorageReference filepath = mImageStorage.child("profile_image").child(current_user_id+".jpg");
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
String download_url = task.getResult().getDownloadUrl().toString();
mUserDatabase.child("image").setValue(download_url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
mProgressDialog.dismiss();
Toast.makeText(SettingsActivity.this,"Success upploading.",Toast.LENGTH_LONG).show();
}
}
});
}else {
Toast.makeText(SettingsActivity.this,"error on upploading.",Toast.LENGTH_LONG).show(); }
mProgressDialog.dismiss();
}
});
Try this:
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Do what you need to do with the URL
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
You must add addOnSuccessListener() after getDownloadUrl() then get the url string inside onSuccess() method.

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

How to fetch image url from firebase Data Storage?

I am using this code below and all I get instead of URL is com.google.android.gms.tasks.zzu#a0a540. How can I get the actual URL?
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
mImageStorage.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUri = filePath.getMetadata().getDownloadUrl();
generatedFilePath = downloadUri.toString();
String downlaodURL = uri.toString();
(mUserDatabase.child("image").setValue(downlaodURL).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
mUploadImage.dismiss();
Toast.makeText(SettingsActivity.this,"image uploaded",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(SettingsActivity.this,"image URL not set",Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
else{
mUploadImage.hide();
Toast.makeText(SettingsActivity.this,"Error uploading image",Toast.LENGTH_SHORT).show();
}
}
});

Categories

Resources