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"));.
Related
This question already has an answer here:
getDownloadURL isn't inputting the link i need
(1 answer)
Closed 2 years ago.
I'm trying to upload an image to Firebase Storage and after that send the URL of this image to Firebase Database. The Uri is correct, but when I try to set it on my object, the method singleDetection.setImage(imagePath) is setting nothing. Here is my code:
Bitmap image = detectedFaceItems.get(0).getImage();
StorageReference storageRef = storage.getReference();
StorageReference imagesRef = storageRef.child("2.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
StorageTask<UploadTask.TaskSnapshot> uploadTask = imagesRef.putBytes(data)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to sent a file", Toast.LENGTH_LONG).show();
}
})
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "Successfully sent a file", Toast.LENGTH_LONG).show();
storageRef.child("2.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
//Doesn't work corretly
String imagePath = uri.toString();
singleDetection.setImage(imagePath);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to get an Uri", Toast.LENGTH_LONG).show();
}
});
}
});
You are uploading the image right, but your call to Firebase after successfully uploading the image using storageRef.child("2.jpg").getDownloadUrl(). not that right as you already don't know the generated Uri which you can get from the snapshot that is returned back with the taskSnapshot.
So replace the below part of code:
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "Successfully sent a file", Toast.LENGTH_LONG).show();
storageRef.child("2.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
//Doesn't work corretly
String imagePath = uri.toString();
singleDetection.setImage(imagePath);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to get an Uri", Toast.LENGTH_LONG).show();
}
});
}
});
With:
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// get upload url
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String imagePath = String.valueOf(task.getResult());
singleDetection.setImage(imagePath);
}
});
}
});
Note: here you've uploaded the image itself, but don't upload its Uri, so you can to decide to upload it to firebase as you'd like.
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();
}
});
}
}
});
}
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());
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
I'm having trouble uploading an image over firebase.
Here's the code:
//...
//Storage
mFirebaseStorage = FirebaseStorage.getInstance();
mUserphotos = mFirebaseStorage.getReference().child("user/#userID");
mTestphotos = mFirebaseStorage.getReference().child("user/testPhotos");
//...
public void uploadImage(Uri uri) {
Uri file = Uri.fromFile(new File("user/testPicture"));
StorageReference testPath = mTestphotos.child("images/"+file.getLastPathSegment());
UploadTask uploadTask = testPath.putFile(file);
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(MainActivity.this, "failure", Toast.LENGTH_SHORT).show();
}
}).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.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(MainActivity.this, "It worked", Toast.LENGTH_SHORT).show();
}
});
//...
To save time yes I am sure the uri is getting the correct photo. There is also more to the uploadImage
//getting the storage reference
// filePath is Uri
// "uploads/" is STORAGE_PATH_UPLOADS
StorageReference sRef = storageReference.child("uploads/" + System.currentTimeMillis() + "." + getFileExtension(filePath));
//adding the file to reference
sRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//displaying success toast
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
//creating the upload object to store uploaded image details
Upload upload = new Upload(editTextName.getText().toString().trim(), taskSnapshot.getDownloadUrl().toString());
//adding an upload to firebase database
String uploadId = mDatabase.push().getKey();
mDatabase.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//displaying the upload progress
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
Try this,
Uri uri = data.getData() ;// your image uri
StorageReference imagePathReference = StorageRef.child("Your path");
Bitmap bmp = null;
try {
bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
// convert bitmap to byte array to save image in firebase storage
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (bmp != null) {
bmp.compress(Bitmap.CompressFormat.JPEG, 60, bos);
}
byte[] dataNew = bos.toByteArray();
uploadTask = imagePathReference.putBytes(dataNew);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.e("firebase ", " addOnFailureListener ");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// u will et download url here.
}
});
private void uploadimage() {
progressbar.setMessage("Uploading Data");
progressbar.setCanceledOnTouchOutside(false);
progressbar.show();
String dateStamp = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:SSS").format(new Date()).toString();
final StorageReference imagepath = storageReference.child("Image" + dateStamp);
imagepath.putFile(selectedImage).addOnSuccessListener(
new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//Toast.makeText(Dashboard.this, "Image Stored Succesfully", Toast.LENGTH_LONG).show();
getimage = taskSnapshot.getDownloadUrl();
// bmp = ((BitmapDrawable) imagepreview.getDrawable()).getBitmap();
Map<String,String> imagemap=new <String,String>HashMap();
imagemap.put("imageurl",getimage);
databaseReference.child(Table_Dashboard).push().setValue(imagemap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
imagepreview.setImageResource(R.mipmap.preview);
progressbar.dismiss();
Toast.makeText(Dashboard.this, "Image Uploaded Succesfully", Toast.LENGTH_LONG).show();
}
}
});
}
});
}
use the above code. it works for me, Hope it will resolve your error