I'm trying to upload a simple byte array into Firebase storage, but my onFailureListener keeps getting called and logging back to me saying that the upload failed. I'm hoping you guys can tell me whats wrong with my code.
At the top I got
//Firebase
private Firebase mRef;
private StorageReference storageRef;
Then in onStart()
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
//Firebase
mRef = new Firebase("link to firebase account");
FirebaseStorage storage = FirebaseStorage.getInstance();
storageRef = storage.getReferenceFromUrl("link to storage");
}
Then in my onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
addImageImageView.setVisibility(View.GONE);
if (requestCode == Constants.REQUEST_CODE && resultCode == RESULT_OK && data != null) {
//First we gotta make sure to add the images to
ArrayList<Image> imagesFromGallery = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);
for (int i = 0; i < imagesFromGallery.size(); i++)
{
try {
//try uploading it
InputStream stream = new FileInputStream(new File(imagesFromGallery.get(i).path));
StorageReference imageStorage = storageRef.child("cardImages/" + "testImages");
UploadTask uploadTask = imageStorage.putStream(stream);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("myStorage","failure :(");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.d("myStorage","success!");
}
});
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Here is my stack trace:
11-13 21:27:00.392 31388-996/com.daprlabs.aaron.swipedeck2 E/StorageException: StorageException has occurred.
User does not have permission to access this object.
Code: -13021 HttpResult: 403
11-13 21:27:00.392 31388-996/com.daprlabs.aaron.swipedeck2 E/StorageException: The server has terminated the upload session
java.io.IOException: The server has terminated the upload session
at com.google.firebase.storage.UploadTask.az(Unknown Source)
at com.google.firebase.storage.UploadTask.ay(Unknown Source)
at com.google.firebase.storage.UploadTask.run(Unknown Source)
at com.google.firebase.storage.StorageTask$5.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
11-13 21:27:00.406 31388-31388/com.daprlabs.aaron.swipedeck2 D/myStorage: failure :(
You either need to sign-in the user or change the security rules to allow public access. This is explained in the documentation for Firebase Storage Security.
For initial development, you can change the rules at the Firebase Console to allow public access:
service firebase.storage {
match /b/project-XXXXXXXXXXXXXX.appspot.com/o {
match /{allPaths=**} {
// Provide access to all users
allow read: if true;
allow write: if true;
}
}
}
I upload images using this code :
private void uploadFile(Bitmap bitmap) {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("Your url for storage");
StorageReference mountainImagesRef = storageRef.child("images/" + chat_id + Utils.getCurrentTimeStamp() + ".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainImagesRef.putBytes(data);
uploadTask.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, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
sendMsg("" + downloadUrl, 2);
Log.d("downloadUrl-->", "" + downloadUrl);
}
});
}
Dependency :
Project Level Gradel : classpath 'com.google.gms:google-services:3.0.0'
App Level Gradel : compile 'com.google.firebase:firebase-storage:9.0.2'
Simply call this method to store your image to firebase.
private void storeImageToFirebase() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8; // shrink it down otherwise we will use stupid amounts of memory
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoUri.getPath(), options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] bytes = baos.toByteArray();
String base64Image = Base64.encodeToString(bytes, Base64.DEFAULT);
//For the API less than 28 (Android version 8 )
//String base64Image = android.util.Base64.encodeToString(bytes, android.util.Base64.DEFAULT);
// we finally have our base64 string version of the image, save it.
firebase.child("pic").setValue(base64Image);
System.out.println("Stored image with length: " + bytes.length);
}
For more details see these examples:
Sample 1
Sample 2
this method worked for me as if todate:
private void uploadImage(Bitmap bitmap) {
progressDialog.show();
final StorageReference ref = storageReference.child("drivers/" + UserDto.getId() + ".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
final UploadTask uploadTask = ref.putBytes(data);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
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 ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downUri = task.getResult();
Log.d("Final URL", "onComplete: Url: " + downUri.toString());
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Upload multilple images to Firebase storage.
It is working for me.
using this library
compile 'com.github.darsh2:MultipleImageSelect:3474549'
At the top
private StorageReference storageRef;
private FirebaseApp app;
private FirebaseStorage storage;
onCreate()
app = FirebaseApp.getInstance();
storage =FirebaseStorage.getInstance(app);
button click action
Gallary.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChatActivity.this, AlbumSelectActivity.class);
intent.putExtra(Constants.INTENT_EXTRA_LIMIT, 10);
startActivityForResult(intent, Constants.REQUEST_CODE);
}
});
Activity result
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<Image> images = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);
Uri[] uri=new Uri[images.size()];
for (int i =0 ; i < images.size(); i++) {
uri[i] = Uri.parse("file://"+images.get(i).path);
StorageReference ref = storage.getReference("photos").child(uri[i].getLastPathSegment());
ref.putFile(uri[i])
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
String content = downloadUrl.toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
})
.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) + "%...");
}
});
}
}
}
Related
I'm trying to make a chatting app in which I want users to upload images, and I'm using Firebase RealTime Database to store user's data. taskSnapshot.downloadUrl() method is deprecated, as I've used a different approach to upload images to Firebase as shown in documentation
https://firebase.google.com/docs/storage/android/upload-files
and this StackOverflow
post:taskSnapshot.getDownloadUrl() is deprecated
But still, image is not uploading to the database.
And I've also tried things like clean project, rebuild project, Invalidate and Restart.
This is the code I'm using to upload images to Firebase RealTime Database:
// ImagePickerButton shows an image picker to upload an image for a
message
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
and then in onActivityResults method :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
Toast.makeText(MainActivity.this, "Signed-In",
Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "Signed-In Cancel",
Toast.LENGTH_SHORT).show();
finish();
} else if (requestCode == RC_PHOTO_PICKER && resultCode ==
RESULT_OK) {
Uri selectedUri = data.getData();
final StorageReference storageReference = mChatPhotosStorageReference.
child(selectedUri.getLastPathSegment());
UploadTask uploadTask = storageReference.putFile(selectedUri);
Task<Uri> uriTask = 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 storageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUrl = task.getResult();
FriendlyMessage message = new FriendlyMessage(null, mUsername, downloadUrl.toString());
mMessageDatabaseReference.push().setValue(message);
}
}
});
This is the Github link for full project: https://github.com/harshabhadra/FriendlyChat
Use this to upload photo to Firebase Storage in byte
private void uploadImage(byte[] data) {
submitButton.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
final String userId = DatabaseContants.getCurrentUser().getUid();
photo_description_edit_text.setVisibility(View.GONE);
StorageMetadata metadata = new StorageMetadata.Builder()
.setContentType("image/webp")
.build();
final String photoName = System.currentTimeMillis() + "_byUser_" + userId;
StorageReference imageRef = StorageConstants.getImageRef(photoName + ".webp");
UploadTask uploadTask = imageRef.putBytes(data, metadata);
final Resources res = getResources();
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = 100.0 * (taskSnapshot.getBytesTransferred() /
taskSnapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
}).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.
Log.d(LOG_TAG, "Image is successfully uploaded: " + taskSnapshot.getMetadata());
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Analytics.registerUpload(activity, userId);
PhotoModel photoModel = new PhotoModel(userId, photoDescription, "none",
0, 0, rotation, photoName + ".webp");
DatabaseContants.getPhotoRef().child(photoName).setValue(photoModel);
Utils.photosUploadedCounter++;
if (Utils.photosUploadedCounter % 2 == 0) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
NotificatonConstants.sendNotification(activity,
res.getString(R.string.failure_title),
res.getString(R.string.failure_message),
NotificatonConstants.UPLOAD_ID);
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
NotificatonConstants.sendNotification(activity,
res.getString(R.string.success_title),
res.getString(R.string.success_message),
NotificatonConstants.UPLOAD_ID);
}
});
}
private void uploadImageToFirebaseStorage() {
StorageReference profileImageRef =
FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");
if (uriProfileImage != null) {
progressBar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.GONE);
profileImageUrl = taskSnapshot.**getDownloadUrl**().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(ProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
taskSnapshot.getDownloadUrl() method not working comes up with red line under it
Edit: see this comment on why the approach in this answer doesn't work:
firebaser here This answer is wrong. While it at first may appear to work (since it compiles) the result of getDownloadUrl().toString() is not a download URL, but a string representation of a Task object. For a better answer, see stackoverflow.com/a/55503926 or the sample in the Firebase documentation.
Original answer below...
In Firebase Storage API version 16.0.1,
the getDownloadUrl() method using taskSnapshot object has changed.
now you can use,
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
to get download url from the firebase storage.
To get imageUrl path from storage use this code:
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if (taskSnapshot.getMetadata() != null) {
if (taskSnapshot.getMetadata().getReference() != null) {
Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String imageUrl = uri.toString();
//createNewPost(imageUrl);
}
});
}
}
}});
that is all 😉
NOTE: Do not forget initialize StorageReference and UploadTask in your uploadFile method.
Try Using this it will download the image from FireBase storage
FireBase Libraries versions 16.0.1
Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String photoStringLink = uri.toString();
}
});
I faced the similar error I solved it with this method. Hope it helps
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> task = taskSnapshot.getMetadata().getReference().getDownloadUrl();
task.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String photoLink = uri.toString();
Map userInfo = new HashMap();
userInfo.put("profileImageUrl", photoLink);
mUserDatabase.updateChildren(userInfo);
}
});
finish();
return;
}
});
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
changeProfilePic(String.valueOf(task.getResult()));//gives image or file string url
}
});
try this code will work for sure
My Google Firebase Plugins in build.gradle(Module: app):
implementation 'com.firebaseui:firebase-ui-database:3.3.1'
implementation 'com.firebaseui:firebase-ui-auth:3.3.1'
implementation 'com.google.firebase:firebase-core:16.0.0'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-auth:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.0.1'
build.gradle(Project):
classpath 'com.google.gms:google-services:3.2.1'
My upload() function and fetching uploaded data from Firebase storage :
private void upload() {
if (filePath!=null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child(new StringBuilder("images/").append(UUID.randomUUID().toString()).toString());
uploadTask = ref.putFile(filePath);
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 ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
progressDialog.dismiss();
// Continue with the task to get the download URL
saveUrlToCategory(downloadUri.toString(),categoryIdSelect);
} else {
Toast.makeText(UploadWallpaper.this, "Fail UPLOAD", Toast.LENGTH_SHORT).show();
}
}
}).addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
progressDialog.setMessage("Uploaded: ");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(UploadWallpaper.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
FOR THOSE WHO ARE USING LATEST FIREBASE VERSION taskSnapshot.getDownloadUrl() method is DEPRECATED or OBSOLETE !!
I'm using Firebase Storage API version 16.0.5 and the task has to be referenced as
someTask.getResult().getMetadata().getReference().getDownloadUrl().toString();
hope this helps!
You wont get the download url of image now using
profileImageUrl = taskSnapshot.**getDownloadUrl**().toString();
this method is deprecated.
Instead you can use the below method
uniqueId = UUID.randomUUID().toString();
ur_firebase_reference = storageReference.child("user_photos/" + uniqueId);
Uri file = Uri.fromFile(new File(mphotofile.getAbsolutePath()));
UploadTask uploadTask = ur_firebase_reference.putFile(file);
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 ur_firebase_reference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
System.out.println("Upload " + downloadUri);
Toast.makeText(mActivity, "Successfully uploaded", Toast.LENGTH_SHORT).show();
if (downloadUri != null) {
String photoStringLink = downloadUri.toString(); //YOU WILL GET THE DOWNLOAD URL HERE !!!!
System.out.println("Upload " + photoStringLink);
}
} else {
// Handle failures
// ...
}
}
});
//upload button onClick
public void uploadImage(View view){
openImage()
}
private Uri imageUri;
ProgressDialog pd;
//Call open Image from any onClick Listener
private void openImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMAGE_REQUEST);
}
private void uploadImage(){
pd = new ProgressDialog(mContext);
pd.setMessage("Uploading...");
pd.show();
if (imageUri != null){
final StorageReference fileReference = storageReference.child(userID
+ "."+"jpg");
// Get the data from an ImageView as bytes
_profilePicture.setDrawingCacheEnabled(true);
_profilePicture.buildDrawingCache();
//Bitmap bitmap = ((BitmapDrawable) _profilePicture.getDrawable()).getBitmap();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = fileReference.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
pd.dismiss();
Log.e("Data Upload: ", "Failled");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
// ...
Log.e("Data Upload: ", "success");
Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String downloadLink = uri.toString();
Log.e("download url : ", downloadLink);
}
});
pd.dismiss();
}
});
}else {
Toast.makeText(getApplicationContext(),"No Image Selected", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null;
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
imageUri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);
_profilePicture1.setImageBitmap(bitmap);
_profilePicture1.setDrawingCacheEnabled(true);
_profilePicture1.buildDrawingCache();
} catch (IOException e) {
e.printStackTrace();
}
if (uploadTask != null && uploadTask.isInProgress()){
Toast.makeText(mContext,"Upload in Progress!", Toast.LENGTH_SHORT).show();
}
else {
try{
uploadImage();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
taskSnapshot.**getDownloadUrl**().toString(); //deprecated and removed
use below code for downloading Url
final StorageReference profileImageRef= FirebaseStorage.getInstance().getReference("profilepics/" + "abc_10123" + ".jpg");
profileImageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
#Override
public void onSuccess(Uri downloadUrl)
{
//do something with downloadurl
}
});
for latest version try
profileImageUrl = taskSnapshot.getStorage().getDownloadUrl().toString();
Try using this:
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
FirebaseStorage Library version 19.0.1 works with
String download_image_path = task.getResult().getUploadSessionUri().toString();
//firebase database
implementation 'com.google.firebase:firebase-database:15.0.0'
//firebase storage
implementation 'com.google.firebase:firebase-storage:15.0.0'
.getDownloadUrl() method is removed from later versions , i have changed it to 15.0.0 and works perfectly fine.You can find these in build.gradle(module:app)
Only that...
taskSnapshot.getStorage().getDownloadUrl();
Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String photoStringLink = uri.toString();
mDatavaseRef.push().setValue(photoStringLink);
}
});
This will work:
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String photoStringLink = uri.toString();
Log.i("urlimage", photoStringLink);
}
});
}
});
Try this:
Uri download_uri ;
final Map<String, String> userData = new HashMap<>();
if (task != null) {
//download_uri = task.getResult().getDownloadUrl();
download_uri = task.getResult().getUploadSessionUri();
}
else {
download_uri= imageUri;
}
userData.put("Image", download_uri.toString());
userData.put("name",username);
userData.put("category",category);
userData.put("status",status);
this is help help me with the last dependencies in 04/2020
// Get a reference to store file at chat_photos/<FILENAME>
final StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
photoRef.putFile(selectedImageUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//When the image has successfully uploaded, get its downloadURL
photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri dlUri = uri;
FriendlyMessage friendlyMessage = new
FriendlyMessage(null, mUsername, dlUri.toString());
Use Firebase storage version 15.0.0.
Uri downloadUrl=taskSnapshot.getDownloadUrl().toString();
you can also use Picasso dependencies . its easy to use for uploading image in firebase.
ActivityFile:
Picasso.get().load(uriImage).into(ImageUri);
app-gradle:
com.squareup.picasso:picasso:2.71828
This will Solve Your Problem....
if(uploadTask.isSuccessfull()){
Task<Uri> uriTask=uploadTask.getResult().getStorage().getDownloadUrl(); while(!uriTask.isSuccessful());
Uri downloadUri=uriTask.getResult();
final String download_url=downloadUri.toString();
}
private void uploadImageTask() {
Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/Pictures/OnShot.jpg"));
StorageReference storageReference = this.storageReference.child("images/" + UUID.randomUUID().toString());
storageReference.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
Log.d(TAG, "Download URL: " + String.valueOf(task.getResult()));
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
I still having this error. What might be wrong? I already changed the permissions, and users to anonymous.
For Java Code
String downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
For Kotlin
val downloadUrl = taskSnapshot.getMetadata()?.getReference()?.getDownloadUrl()?.toString()
there is nothing wrong with the depencies. You just have to downgrade your firebase depencies. This is because it hasnt been updated yet..
imageView=(ImageView)findViewById(R.id.dd);
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://MyProject.appspot.com/");
storageRef.child("MyFolder/MyPict.jpg").getDownloadUrl().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Glide.with(MainActivity.this).load(uri).into(imageView);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
But.. "Unfortunately YourApp has stoped" is displayed..
Can you help me please
I hope you give rules in firebase storage as reading and write true.
on button click used below method ..
private void uploadImage() {
// Start by getting our StorageReference
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference rootRef = storage.getReference();
StorageReference bearRef = rootRef.child("images/bear.jpg");
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
// Get the data from the image as bytes
ImageView bearImage = getSelectedBearImage();
bearImage.setDrawingCacheEnabled(true);
bearImage.buildDrawingCache();
Bitmap bitmap = bearImage.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
// Upload it to our reference
UploadTask uploadTask = bearRef.putBytes(data);
buttonDownload.setEnabled(false);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Log.w(LOG_TAG, "Upload failed: " + exception.getMessage());
}
}).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();
progressDialog.dismiss();
Log.d(LOG_TAG, "Download Url: " + downloadUrl);
buttonDownload.setEnabled(true);
}
});
}
and I hope you add internet permission on android manifest file...
<uses-permission android:name="android.permission.INTERNET"/>
for information you can refer this link..
More Information For Storage :
https://firebase.google.com/docs/storage/
For Upload & Download :
https://www.simplifiedcoding.net/firebase-storage-tutorial-android/
use storage.getStorage().getReferenceFromUrl("gs://MyProject.appspot.com/");
I have created an app running with Firebase Storage. The idea is that you select an Image from your Photo Gallery and then Upload it to Firebase Storage. The connection with Firebase seems to work fine, I can select an Image. The problem arises when I push the Submit Button to upload it to Firebase.
When I click it one time, nothing happens.
When I click it a few times, I get the message "an unknown error occurred, please check the HTTP result code and inner exception"..
What should I do, looking for advice..
From the Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
From the Activity:
public class PostActivity extends AppCompatActivity {
private static final int GALLERY_REQUEST = 2;
private Uri uri = null;
private ImageButton imageButton;
private EditText editName;
private EditText editDescription;
private StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
//reference the two edittext Views, initialize them
editName = (EditText) findViewById(R.id.editName);
editDescription = (EditText) findViewById(R.id.editDescription);
//add the reference to the storagereference, initialize it
storageReference = FirebaseStorage.getInstance().getReference();
}
public void ImageButtonClicked (View view){
Intent galleryintent = new Intent (Intent.ACTION_GET_CONTENT);
galleryintent.setType("Image/*");
startActivityForResult(galleryintent, GALLERY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
uri = data.getData();
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setImageURI(uri);
}
}
public void submitButtonClicked (View view){
String titleValue = editName.getText().toString().trim();
String titleDescription = editDescription.getText().toString().trim();
if (!TextUtils.isEmpty(titleValue) && !TextUtils.isEmpty(titleDescription)){
StorageReference filePath = storageReference.child("PostImage").child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadurl = taskSnapshot.getDownloadUrl();
Toast.makeText(PostActivity.this,"uploadcomplete",Toast.LENGTH_LONG).show();
}
});
filePath.putFile(uri).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
Try this method for image upload to firebase storage:
private void uploadMethod() {
progressDialog();
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
StorageReference storageReferenceProfilePic = firebaseStorage.getReference();
StorageReference imageRef = storageReferenceProfilePic.child("Your Path" + "/" + "Image Name" + ".jpg");
imageRef.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//if the upload is successful
//hiding the progress dialog
//and displaying a success toast
dismissDialog();
String profilePicUrl = taskSnapshot.getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
//if the upload is not successful
//hiding the progress dialog
dismissDialog();
//and displaying error message
Toast.makeText(getActivity(), exception.getCause().getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//calculating progress percentage
// double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
// //displaying percentage in progress dialog
// progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
}
I have found an answer through the code of Rahul Chandrabhan.
What I have changed is to remove the last part of the following method:
StorageReference filePath =
storageReference.child("PostImage").child(uri.getLastPathSegment());
TO
StorageReference filePath = storageReference.child("PostImage");
To perform image upload on firebase use below method:
void uploadFile(String pathToFile, String fileName, String serverFolder, String contentType) {
if (pathToFile != null && !pathToFile.isEmpty()) {
File file = new File(pathToFile);
if (file.exists()) {
Uri uri = Uri.fromFile(new File(pathToFile));
// Create a storage reference from our app
mStorageRef = mFirebaseStorage.getReference();
// Create a reference to "mountains.jpg"
//StorageReference mountainsRef = storageRef.child(fileName);
// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef = mStorageRef.child(serverFolder+"/" + fileName);
StorageMetadata metadata = null;
if (contentType != null && !contentType.isEmpty()) {
// Create file metadata including the content type
metadata = new StorageMetadata.Builder()
.setContentType(contentType)
.build();
}
if (metadata != null) {
uploadFileTask = mountainImagesRef.putFile(uri, metadata);
} else {
uploadFileTask = mountainImagesRef.putFile(uri);
}
uploadFileTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
hideProgressDialog();
exception.printStackTrace();
Log.e(TAG,exception.getMessage());
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadFailure(exception.getMessage());
}
}
});
uploadFileTask.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.
hideProgressDialog();
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Log.e(TAG, "Upload is success "+ downloadUrl);
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadSuccess("Upload is success "+ downloadUrl.toString(), downloadUrl.toString());
}
}
});
// Observe state change events such as progress, pause, and resume
uploadFileTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
hideProgressDialog();
double progressPercent = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressPercent = Double.parseDouble(FirebaseUtil.formatDecimal(progressPercent,2));
Log.e(TAG, "File Upload is " + progressPercent + "% done");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadProgress(progressPercent);
}
}
});
uploadFileTask.addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
#Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
hideProgressDialog();
Log.e(TAG, "Upload is paused");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadPaused("Upload is paused");
}
}
});
}
else
{
hideProgressDialog();
Log.e(TAG, "Upload file does not exists");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadFailure("Upload file does not exists");
}
}
}else
{
hideProgressDialog();
Log.e(TAG,"pathToFile cannot be null or empty");
if (firebaseUploadCallback!=null)
{
firebaseUploadCallback.onFirebaseUploadFailure("pathToFile cannot be null or empty");
}
}
}
Make a call this method as below:
public void uploadDummyPicture(String email, String imagePath){
if (imagePath == null) {
return;
}
if (!isValidEmail(email)) {
return;
}
String serverFolder = "dummy_images/" + email; //path of your choice on firebase storage server
String fileName = "DummyPhoto.png";
uploadFile(imagePath, fileName, serverFolder, "image/png");
showProgressDialog();
}
Make sure to check the firebase storage rules before using above code as explained here. If the rules have firebase authentication required, then first complete firebase authentication of the current user and then start uploading the file.
I hope this answer will you solve your problem.
In my case, the URI which I was fetching on the onActivityResult function was just not in the right format.
Previously I was parsing like this
uri=Uri.parse(your image path)
but after changing to this it worked
uri=Uri.fromFile(new File(your image path))
the upload function
public void upload()
{
if(uri!=null)
{
progressBar.setVisibility(View.VISIBLE);
progressBar_tv.setVisibility(View.VISIBLE);
Log.i("URI",uri.getPath());
UploadTask uploadTask=sRef.putFile(uri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(VideoEditAndUploadActivity.this, "Upload Failed:"+e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();;
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(VideoEditAndUploadActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
progressBar_tv.setVisibility(View.INVISIBLE);
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
updateUploadProgress(snapshot);
}
});
}
else{
Toast.makeText(this, "Video Uri is null: please choose a video first!", Toast.LENGTH_SHORT).show();
}
}
the update progress bar function
#SuppressLint("DefaultLocale")
private void updateUploadProgress(UploadTask.TaskSnapshot snapshot) {
long fileSize=snapshot.getTotalByteCount();
long uploadBytes=snapshot.getBytesTransferred();
long progress=(100*uploadBytes)/fileSize;
progressBar.setProgress((int) progress);
progressBar_tv.setText(String.format("%d%%", progress));
}
If you are using rxjava then you could use the following snippet
public Observable<FirebaseFile> uploadImageToFirebase(#NonNull Uri file) {
return Observable.create(emitter -> {
try {
final StorageReference conversationReference = reference.child("some-identifier");
final File localFile = new File(file.getPath());
final StorageReference fileReference = conversationReference
.child(UUID.randomUUID().toString().toLowerCase(Locale.ROOT) + "-" + localFile.getName());
final UploadTask uploadTask = fileReference.putFile(file);
uploadTask.continueWithTask(task -> {
if (task.isSuccessful()) {
return fileReference.getDownloadUrl();
} else {
if (task.getException() != null) {
throw task.getException();
} else {
throw new RuntimeException("Error uploading file to firebase storage");
}
}
}).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
final Uri downloadUri = task.getResult();
if (downloadUri != null) {
emitter.onNext(new FirebaseFile(file.getPath(), downloadUri.toString(), 100));
emitter.onComplete();
} else {
if (!emitter.isDisposed()) {
emitter.onError(new RuntimeException("Error uploading stream to firebase storage"));
}
}
} else {
if (!emitter.isDisposed()) {
emitter.onError(new RuntimeException("Error uploading file to firebase storage"));
}
}
});
uploadTask.addOnProgressListener(taskSnapshot -> {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
emitter.onNext(new FirebaseFile(file.getPath(), null, (int) progress));
});
} catch (Exception e) {
if (!emitter.isDisposed()) {
emitter.onError(e);
}
}
});
}
Where
FirebaseStorage fs = FirebaseStorage.getInstance()
and
StorageReference StorageReference = firebaseStorage.getReference("some-identifier-if-any");```
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