how to upload multiple images in firebase - android

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

Related

Firebase Storage - Link not created

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

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

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

Unable to store Firebase Storage Image into a folder

My code is :
String path= Environment.getExternalStorageDirectory()+File.separator+"Cloud_data"+File.separator+"Images";
file= new File(path);
if(!file.isDirectory())
{
file.mkdirs();
}
storageReference2.getFile(file)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(DownloadFiles.this, "path"+file, Toast.LENGTH_LONG).show();
text1.setText(String.valueOf(file)+"."+taskSnapshot.getStorage());
Toast.makeText(DownloadFiles.this, "File Downloaded Successfully", Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onProgress(FileDownloadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
Toast.makeText(DownloadFiles.this, "Progress: "+(int)progress+"%", Toast.LENGTH_SHORT).show();
}
});
I created a folder Cloud_data/image but image are not saving in this folder. How can I resolve my issue?
The picture path you used may be used as you would write below.
FireabaseStorage firebaseStorage = FirebaseStorage.getInstance();
StorageReference storageReference = firebaseStorage.getReference();
storageReference.child("Cloud_data/"+
RandomImageName);
storageReference .putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Toast.makeText(DownloadFiles.this, "path"+file, Toast.LENGTH_LONG).show();
text1.setText(String.valueOf(file)+"."+taskSnapshot.getStorage());
Toast.makeText(DownloadFiles.this, "File Downloaded Successfully", Toast.LENGTH_SHORT).show()
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(DownloadFiles.this, "Error", Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot)
{
double progress=(100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
Toast.makeText(DownloadFiles.this, "Progress: "+(int)progress+"%", Toast.LENGTH_SHORT).show();
}
});
I hope I helped.
File file is a directory so you cannot use it in .getFile(file) as then file should point to a file.
Better try .getFile(new File(file, "myfile.jpg"));.

Categories

Resources