getting same URL when uploading to firebase storage - Android - android

Whenever I'm trying to upload a file to firebase storage, and then retrieve the download URL for it, I'm getting the same URL even when different files are uploaded. The files do get uploaded, but the URL received is similar for every upload
downloadURL = new Uri[1];
UploadTask uploadTask = mChatPhotosStorageReference
.child(selectedImageUri.getLastPathSegment())
.putFile(selectedImageUri);
Log.v("SelectedImage: ", selectedImageUri.getLastPathSegment());
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 mChatPhotosStorageReference.getDownloadUrl();
}
})
.addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
downloadURL[0] = task.getResult();
//passing downloadUri to database to store with chat messages
ShutUpMessages shutUpMessages = new ShutUpMessages(null, mUsername, downloadURL[0].toString());
mMessagesDatabaseReference.push().setValue(shutUpMessages);
mProgressbar.setVisibility(ProgressBar.INVISIBLE);
Toast.makeText(MainActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(MainActivity.this, "File Upload failed", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_SHORT).show();
mProgressbar.setVisibility(ProgressBar.INVISIBLE);
}
});

Related

how to get download urls of multiple image uploads to firebase storage

I am uploading two "user-selected" images to firebase storage and getting their URL to save to the firestore, but the URLs save point to only one of the pictures although they don't appear to be the same.
there is a similar question but about swift and it doesn't answer my question, here is the URL to that.
get download url from multiple file upload firebase storage
I tried getting the download links with ref.getDownloadUrl() but that gave wrong URLs and tasksnapshot.getDownloadUrl() doesn't work anymore.
I tried reading lots of answers but nothing helped most are outdated with tasksnapshot.getDownloadUrl() method.
if (profileImageUri != null) {
//upload first image
profileImageRef.putFile(profileImageUri).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 profileImageRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
profileImageUrl = String.valueOf(downloadUri);
saveUserInfo(); // method to save the URLs along with other info
} else {
Toast.makeText(EditProfile.this, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
btSaveInfo.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
});
}
if (coverImageUri != null) {
// Upload second image
profileImageRef.putFile(coverImageUri).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 profileImageRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadCUri = task.getResult();
coverImageUrl = String.valueOf(downloadCUri);
Toast.makeText(getApplicationContext(), "Cover Picture Uploaded", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(EditProfile.this, "Cover picture upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
the two images are uploaded I can see them in my firebase console but the URLs saved in firestore both load the same image although they are not the same, they look like this,
https://firebasestorage.googleapis.com/v0/b/sefnetapp-39b37.appspot.com/o/profilePics%2F1561103180500.jpg?alt=media&token=8dd5ee93-9bbc-46ee-89b9-fb5ae5b36128
https://firebasestorage.googleapis.com/v0/b/sefnetapp-39b37.appspot.com/o/profilePics%2F1561103180500.jpg?alt=media&token=c153c59b-c6b3-428b-a845-3db3b19a38e3
how do I get the two URLs that will load the two pictures that I uploaded not only one
thanks for your help, much appreciated.
I just realized that I wasn't saving my info after uploading the cover image, I added the saveInfo method in my onComplete of cover image upload method also and it works fine now.
final StorageReference profileImageRef = FirebaseStorage.getInstance()
.getReference(SefnetContract.PROFILE_PICS_REF + System.currentTimeMillis() + ".jpg");
// Upload profile picture
if (profileImageUri != null) {
progressBar.setVisibility(View.VISIBLE);
profileImageRef.putFile(profileImageUri).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 profileImageRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
profileImageUrl = String.valueOf(downloadUri);
saveUserInfo();
} else {
Toast.makeText(EditProfile.this, "upload failed: "
+ task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
});
}
if (coverImageUri != null) {
// Upload cover picture
progressBar.setVisibility(View.VISIBLE);
profileImageRef.putFile(coverImageUri).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 profileImageRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
Uri downloadCUri = task.getResult();
coverImageUrl = String.valueOf(downloadCUri);
saveUserInfo();
Toast.makeText(getApplicationContext(), "Cover Picture Uploaded", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(EditProfile.this, "Cover picture upload failed: "
+ task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
I still feel like it could be done in a better way so if you know of a method better than this please share. I would like a method in which I can stop the user from initializing the upload method too many times by clicking the button repeatedly, thank you

How to Upload and Retrieve image in latest firebase storage after update

I am trying to upload and retrieve the image and follow all the results available at Stack and tutorials but none of example help me.
how to upload an image on button click in latest firebase storage
I am following this tutorial
https://www.simplifiedcoding.net/firebase-storage-example/
StorageReference reference= storageReference.child(System.currentTimeMillis()+ "."+getFileExtension(filePath));
mUploadTask= reference.putFile(filePath);
Task<Uri> urlTask = mUploadTask.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 storageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
} else {
// Handle failures
// ...
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
You are doing it right to upload the image, after you return the storageReference.getDownloadUrl(), just set that value into your firebase database.
StorageReference reference= storageReference.child(System.currentTimeMillis()+ "."+getFileExtension(filePath));
mUploadTask= reference.putFile(filePath);
Task<Uri> urlTask = mUploadTask.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 storageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
mDatabaseRef.child("images").child("imageUrl").setValue(downloadUri.toString());
} else {
// Handle failures
// ...
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
You will need to request that image url String from firebase and after that, to show the image in any ImageView use Picasso or Glide to load it.

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

How can I get the download URL in String from firebase storage inside "addOnSuccessListener"

This is my approach to upload an image file and getting the download link
UploadTask uploadTask = profileImageRef.putBytes(data);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String fileUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
Toast.makeText(UserProfile.this, "Uploaded Successfully!", Toast.LENGTH_SHORT).show();
}});
When I logged fileUrl it displays a String like this
com.google.android.gms.tasks.zzu#6ee8ba8
Someone please give me a solution to get the download url.
you can use this,
UploadTask uploadTask = profileImageRef.putBytes(data);
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 profileImageRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
} else {
// Handle failures
// ...
}
}
});

Firebase storage is error during upload to database

i am trying to use firebase storage but i keep getting a fatal error when i upload and want to send it to my database. the upload is successful but i try to get the download url to my database and i get this error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.apps.ayodkay.services, PID: 10693
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
at com.apps.ayodkay.services.Profile$9.onComplete(Profile.java:550)
at com.google.android.gms.tasks.zzj.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5753)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
this is code i used from the documentation in firebase storage
if (mImageUri != null) {
Date date = new Date();
long time = date.getTime();
Uri file = Uri.fromFile(new File("path/to/images/" + time));
final StorageReference fileReference = mStorageRef.child("images/" + file.getLastPathSegment());
mUploadTask = fileReference.putFile(mImageUri);
// Register observers to listen for when the download is done or if it fails
mUploadTask.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) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
// ...
}
});
Task<Uri> urlTask = mUploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw Objects.requireNonNull(task.getException());
}
// Continue with the task to get the download URL
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String uri = downloadUri.toString();
mUsernameDatabase.child("image").setValue(uri);
Toast.makeText(Profile.this, "upload Done", Toast.LENGTH_SHORT).show();
mprogress.setVisibility(View.GONE);
} else {
Toast.makeText(Profile.this, "Error uploaing", Toast.LENGTH_SHORT).show();
}
}
});
// [END upload_get_download_url]
}
i tried to use another method and it worked perfectly. i used the UserProfileChangeRequest method instend of send it to my database, i set a new user photo url
Task<Uri> urlTask = mUploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw Objects.requireNonNull(task.getException());
}
// Continue with the task to get the download URL
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
FirebaseUser user = mAuth.getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setPhotoUri(downloadUri)
.build();
user.updateProfile(profileUpdates).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(Profile.this, "upload Done", Toast.LENGTH_SHORT).show();
mprogress.setVisibility(View.GONE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
} else {
Toast.makeText(Profile.this, "Error uploaing", Toast.LENGTH_SHORT).show();
}
}
});

Categories

Resources