Firebase Storage - Link not created - android

I am trying to upload an image and a document to the firebase storage and upload the links created from both to the Real-Time DB, everything happening on a button's click.
But in the firebase DB, the links are not uploaded while the other text I upload along with them is there.
Storage upload code:
updata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//before uploading both the doc and img..
progressDialog.setTitle("Uploading Images");
progressDialog.show();
final UploadData uploadData=new UploadData();
if(ImgPathUri!=null){
StorageReference str=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(ImgPathUri));
str.putFile(ImgPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String ImgLink=uri.toString();
linkimg=ImgLink;
uploadData.setImgURL(linkimg);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(addEventActivity.this, "fucked ra", Toast.LENGTH_SHORT).show();
finished=false;
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}
if(DocPathUri!=null){
StorageReference storageReference1=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(DocPathUri));
storageReference1.putFile(DocPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String DocLink=uri.toString();
linkdoc=DocLink;
uploadData.setDocURL(linkdoc);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("TAG_FOR_FAILURE LOG", "On Failure: The exception", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finished=false;
Toast.makeText(addEventActivity.this, "doc fucked", Toast.LENGTH_SHORT).show();
}
});
}
progressDialog.dismiss();
String info=infoText.getText().toString();
String event=eventName.getText().toString();
uploadData.setName(event);
uploadData.setInfo(info);
//uploading the event name,info and other file links to the RTDB under the event name
databaseReference.child(event).setValue(uploadData);
}
});
}
Where updata is the button, UploadData is the class for holding those all those values...
After I click the button the image is stored in the Storage while the Database holds nothing but,
data {
name:"given name"
info:"given info"
}
while it has to have included the ImgLink and DocLink.
Where does it lose track?

Try this code
Declare this object globally
Uri uri;
Set uri when user fetches the Image from the gallery
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
jimg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here sUrl will have downloadURL
private void uploadImage() {
try {
final StorageReference ref = storageReference.child( UUID.randomUUID().toString() );
//uploads the image
ref.putFile( uri ).addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener( new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final Uri downloadUrl = uri;
sUrl = downloadUrl.toString();
}
} ).addOnFailureListener( new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
} );
}
} );
}catch (Exception e){}
}

Each onSuccess method is called asynchronously, after the call to the server has completed. Since this takes time, you main code continues, and this means you're writing to the database, before the download URL is available.
It's easiest to see this if you place some log statements in your code:
Log.i("STORAGE", "Starting to upload image data");
StorageReference storageReference1=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(DocPathUri));
storageReference1.putFile(DocPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.i("STORAGE", "Image data uploaded, getting download URL");
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.i("STORAGE", "Got download URL");
String DocLink=uri.toString();
linkdoc=DocLink;
uploadData.setDocURL(linkdoc);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("TAG_FOR_FAILURE LOG", "On Failure: The exception", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finished=false;
Toast.makeText(addEventActivity.this, "doc fucked", Toast.LENGTH_SHORT).show();
}
});
...
uploadData.setName(event);
uploadData.setInfo(info);
Log.i("STORAGE", "Writing info to database");
databaseReference.child(event).setValue(uploadData);
The output of this is:
Starting to upload image data
Writing info to database
Image data uploaded, getting download URL
Got download URL
This is probably not what you expected, but it is working as intended, and completely explains why the download URL isn't written to the database: by the time you write to the database, the download URL hasn't been loaded yet.
The solution to this problem is always the same: any code that requires the download URL, need to be inside the onSuccess method that gets called when the download URL is retrieved (or at least needs to be called from there).
So something like:
updata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//before uploading both the doc and img..
progressDialog.setTitle("Uploading Images");
progressDialog.show();
final UploadData uploadData=new UploadData();
if(ImgPathUri!=null){
StorageReference str=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(ImgPathUri));
str.putFile(ImgPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String ImgLink=uri.toString();
linkimg=ImgLink;
uploadData.setImgURL(linkimg);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(addEventActivity.this, "fucked ra", Toast.LENGTH_SHORT).show();
finished=false;
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}
if(DocPathUri!=null){
StorageReference storageReference1=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(DocPathUri));
storageReference1.putFile(DocPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String DocLink=uri.toString();
linkdoc=DocLink;
uploadData.setDocURL(linkdoc);
progressDialog.dismiss();
String info=infoText.getText().toString();
String event=eventName.getText().toString();
uploadData.setName(event);
uploadData.setInfo(info);
//uploading the event name,info and other file links to the RTDB under the event name
databaseReference.child(event).setValue(uploadData);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("TAG_FOR_FAILURE LOG", "On Failure: The exception", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finished=false;
Toast.makeText(addEventActivity.this, "doc fucked", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}

Related

Why isn't my image showing when retrieved from Firebase eventhough it was successfully uploaded?

This is my code.
private void uploadPattern() {
if (mImageUri != null) {
final StorageReference fileReference = mStorageRef.child(System.currentTimeMillis() + "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(PatternArranger.this, "Save Successful", Toast.LENGTH_SHORT).show();
//Upload upload = new Upload(mEditPatternName.getText().toString().trim(),
//taskSnapshot.getUploadSessionUri().toString());
//String uploadId = mDatabaseRef.push().getKey();
//mDatabaseRef.child(uploadId).setValue(upload);
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while ( !urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
//Log.d(TAG, "onSuccess: firebase download url: " + downloadUrl.toString()); //use if testing...don't need this line.
Upload upload = new Upload(mEditPatternName.getText().toString().trim(),downloadUrl.toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(PatternArranger.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No pattern selected", Toast.LENGTH_SHORT).show();
}
}
By using a while loop, you are likely missing out on important debugging information to solve your issue. In your code, it is likely that urlTask has failed and urlTask.isSuccessful() will never evaluate to true which is causing an infinite loop.
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while ( !urlTask.isSuccessful());
To fix this, properly attach listeners to the Task returned by each operation and log their results.
taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUri) {
Log.d(TAG, "getDownloadUrl.onSuccess: obtained download URI: " + downloadUri.toString());
Upload upload = new Upload(mEditPatternName.getText().toString().trim(),downloadUri.toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload)
.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess() {
Log.d(TAG, "setValue.onSuccess: uploaded & saved to database");
// TODO: Update UI to show image/completion message
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Log.d(TAG, "setValue.onFailure: error occured - " + exception.message);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Log.d(TAG, "getDownloadUrl.onFailure: error occured - " + exception.message);
}
});

Cannot Delete An Image From Firebase Storage

I am trying to replace an image in Firebase storage with a new one by first deleting the old and then adding the new. The problem is the deletion. I cannot seem to get it to work. Here is the relevant code:
private void uploadFile(){
progressBar.setVisibility(View.VISIBLE);
db2 = FirebaseFirestore.getInstance().collection("Users").document(id);
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "."+ getFileExtension(imageuri));
mUploadTask = fileReference.putFile(imageuri).
addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
db2.update("Image URI",downloadUrl.toString()).addOnSuccessListener(
new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(settings_activity
.this, "DP change added." ,
Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(settings_activity.this, "FIRESTROE ERROR "+e.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(settings_activity.this, "FILE STRORAGE "+e.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(settings_activity.this, "DELETION ERROR: "+e.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
This is the storage reference I used in the code above:
FirebaseStorage.getInstance().getReference().child("profile_pics/"+FirebaseAuth.getInstance().getCurrentUser().getUid());

Pushing Firebase storage download URLs to Firebase cloud Firestore

How can I push the download URL of Firebase storage files to the Firestore cloud? I have a project that can upload PDF files to Firestore storage, but I can't push the download URL of the uploaded files to the Firestore cloud.
I need to catch the upload URL for every single file and send it to the document in the firestore to be able to download it. I'm uploading and downloading PDF files.
Here is my code:
public class pdfUploader extends AppCompatActivity {
private StorageReference mStorageRef;
Button upload;
Button select;
int CODE=215;
private CollectionReference dbFirestore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_uploader);
mStorageRef = FirebaseStorage.getInstance().getReference();
upload = findViewById(R.id.upload);
select = findViewById(R.id.choose);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectFile();
}
});
}
public void selectFile () {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i,"Select a file"), CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String filePath = data.getDataString();
Uri SelectedFileLocation=Uri.parse(filePath);
UploadFile(SelectedFileLocation);
super.onActivityResult(requestCode, resultCode, data);
}
public void UploadFile( Uri file) {
Toast.makeText(this, "Please wait.. the file is uploading!", Toast.LENGTH_SHORT).show();
//Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = mStorageRef.child(Objects.requireNonNull(file.getLastPathSegment()));
riversRef.putFile(file)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(pdfUploader.this, "Upload Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(pdfUploader.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
});
}
}
Assign this Variable on Top
FirebaseFirestore db;
//In oncreateView we have to assign now db so.
db = FirebaseFirestore.getInstance();
Code for get File uri :
riversRef.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
riversRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
//After upload Complete we have to store the Data to firestore.
Map<String, Object> file = new HashMap<>();
file.put("url", downloadUrl.toString()); // We are using it as String because our data type in Firestore will be String
db.collection("/*Put you're collection name*/").document("/*And Document name Here*/")
.set(file)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
}
}
});
If download url expires there's better way to store you're image file in you're storage and firestore
Code :
riversRef.putFile(file)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String path = //Put path of storage it will be something like [images/filename.jpg(Put your extension of file)] this path from firebase storage
Map<String, Object> file = new HashMap<>();
file.put("url", path); // We are using it as String because our data type in Firestore will be String
db.collection("/*Put you're collection name*/").document("/*And Document id Here*/")
.set(file)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(pdfUploader.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
});
the above code will be useful and better when you're dealing with images and read this docs for further details

how to upload multiple images in firebase

i want to upload images in firebase from the four boxes and getdownload url for each
I am writing an app to test out firebase where a user can upload product with images. I'm having issues with the upload as although the pictures are stored, they are not linked to the product (images array not being passed?) and LeakCanary signals an outofmemory error. All help and input appreciated.
Here's my Product Model
final ProgressDialog mDialog = new ProgressDialog(this);
mDialog.setMessage("Uploading....");
mDialog.show();
newFood = new Food();
final String imageName = UUID.randomUUID().toString();
final StorageReference imageFolder = storageReference.child("images/" + Common.imgFront.getLastPathSegment());
final StorageReference imageFolder1 = storageReference.child("images/" + Common.imgBack.getLastPathSegment());
final StorageReference imageFolder2 = storageReference.child("images/" + Common.imgRight.getLastPathSegment());
final StorageReference imageFolder3 = storageReference.child("images/" + Common.imgLeft.getLastPathSegment());
imageFolder.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Toast.makeText(FileUpload.this, "Uploaded !!!", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
newFood.setName(carName.getText().toString());
newFood.setEngine(carEngine.getText().toString());
newFood.setPrice(carPrice.getText().toString());
newFood.setTransmission(carTransmission.getText().toString());
newFood.setCondition(carCondition.getText().toString());
newFood.setOther(otherDescription.getText().toString());
newFood.setDiscount(carDiscount.getText().toString());
newFood.setMenuId(categoryId);
newFood.setImagefront(uri.toString());
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
mDialog.dismiss();
Toast.makeText(FileUpload.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
imageFolder1.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Toast.makeText(FileUpload.this, "Uploaded !!!", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
newFood.setImageback(uri.toString());
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
mDialog.dismiss();
Toast.makeText(FileUpload.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
imageFolder2.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Toast.makeText(FileUpload.this, "Uploaded !!!", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
newFood.setImageright(uri.toString());
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
mDialog.dismiss();
Toast.makeText(FileUpload.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
imageFolder3.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mDialog.dismiss();
Toast.makeText(FileUpload.this, "Uploaded !!!", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
newFood.setImageleft(uri.toString());
if (newFood !=null)
{
foods.push().setValue(newFood);
Snackbar.make(rootLayout, "New Car "+newFood.getName()+ " was added",Snackbar.LENGTH_SHORT)
.show();
}
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
mDialog.dismiss();
Toast.makeText(FileUpload.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
There is no API to upload or download multiple images at the same time with Firebase storage.
You can check a workaround on this other stack overflow question

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

Categories

Resources