I'am trying to update a photo on Firebase Storage.
Rules for Storage are public and all libraries are up to date.
For bucket I'm using the one from my firebase console.
Fatal Exception:
java.lang.IllegalArgumentException: The supplied bucketname is not
available to this project. at
com.moose.android.AddPostActivity.onClick(AddPostActivity.java:163)
Bitmap bitmap = imageBitmap;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
byte[] data = baos.toByteArray();
FirebaseStorage mFirebaseStorage = FirebaseStorage.getInstance();
***StorageReference mStorageRef = mFirebaseStorage.getReferenceFromUrl("gs://bucketname.appspot.com"); //line 163***
final StorageReference photoRef = mStorageRef.child("posts_images/mooseImg" + getCurrentDateTime() + ".jpg");
UploadTask uploadTask = photoRef.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();
Firebase createNewPost = new Firebase(FirebaseURL);
Firebase alanRef = createNewPost.push();
Map<String, Object> nickname = new HashMap<String, Object>();
nickname.put("createdAt", getCurrentDateTime());
nickname.put("imageURL", downloadUrl.toString());
/*nickname.put("latitude", 20.1814);
nickname.put("longitude", 72.1781);*/
nickname.put("latitude", prefs.getLatitude());
nickname.put("longitude", prefs.getLongitude());
nickname.put("objectId", alanRef.getKey());
nickname.put("ownerId", prefs.getUserUId());
nickname.put("postText", editTextNewPostMsg.getText().toString());
nickname.put("replies", 0);
nickname.put("reportCount", 0);
nickname.put("score", 0);
nickname.put("updatedAt", getCurrentDateTime());
alanRef.setValue(nickname, new Firebase.CompletionListener() {
#Override
public void onComplete(FirebaseError firebaseError, Firebase firebase) {
dismissProgressDialog();
Toast.makeText(getApplicationContext(), "your post have been added.", Toast.LENGTH_LONG).show();
finish();
}
});
// LogUtil.debug("StorageRef = " + mStorageRef);
}
});
It should be in your google-services.json file with tag "storage_bucket"
"project_info": {
"project_number": "816275527980",
"firebase_url": "https://project-8693710910123456789.firebaseio.com",
"project_id": "project-8693710910123456789",
"storage_bucket": "project-8693710910123456789.appspot.com"
},
Related
I wanted to convert my code so that it would upload the data to the Firestore database since its better for what I need.
private void uploadData(final String titl, final String description) {
// show the progress dialog box
pd.setMessage("Publishing Post");
pd.show();
final String timestamp = String.valueOf(System.currentTimeMillis());
String filepathname = "Posts/" + "post" + timestamp;
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] data = byteArrayOutputStream.toByteArray();
// initalising the storage reference for uploading the data
StorageReference storageReference1 = FirebaseStorage.getInstance().getReference().child(filepathname);
storageReference1.putBytes(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// getting the url of image uploaded
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
String downloadUri = uriTask.getResult().toString();
if (uriTask.isSuccessful()) {
HashMap<Object, String> hashMap = new HashMap<>();
hashMap.put("uid", uid);
hashMap.put("uname", name);
hashMap.put("uemail", email);
hashMap.put("udp", dp);
hashMap.put("title", titl);
hashMap.put("description", description);
hashMap.put("uimage", downloadUri);
hashMap.put("ptime", timestamp);
hashMap.put("plike", "0");
hashMap.put("pcomments", "0");
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Posts").add(data)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
pd.dismiss();
Toast.makeText(PostBlogActivity.this, "Published", Toast.LENGTH_LONG).show();
title.setText("");
des.setText("");
image.setImageURI(null);
imageuri = null;
startActivity(new Intent(PostBlogActivity.this, DashboardActivity.class));
PostBlogActivity.this.finish();
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(PostBlogActivity.this, "Failed", Toast.LENGTH_LONG).show();
}
});
}
Honestly I don't know why its doing this since it has no reason to.
I also try doing it this way as well
private void uploadData(final String titl, final String description) {
// show the progress dialog box
pd.setMessage("Publishing Post");
pd.show();
final String timestamp = String.valueOf(System.currentTimeMillis());
String filepathname = "Posts/" + "post" + timestamp;
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] data = byteArrayOutputStream.toByteArray();
// initalising the storage reference for uploading the data
StorageReference storageReference1 = FirebaseStorage.getInstance().getReference().child(filepathname);
storageReference1.putBytes(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// getting the url of image uploaded
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
String downloadUri = uriTask.getResult().toString();
if (uriTask.isSuccessful()) {
HashMap<Object, String> hashMap = new HashMap<>();
hashMap.put("uid", uid);
hashMap.put("uname", name);
hashMap.put("uemail", email);
hashMap.put("udp", dp);
hashMap.put("title", titl);
hashMap.put("description", description);
hashMap.put("uimage", downloadUri);
hashMap.put("ptime", timestamp);
hashMap.put("plike", "0");
hashMap.put("pcomments", "0");
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Posts").document(timestamp).set(data)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
pd.dismiss();
Toast.makeText(PostBlogActivity.this, "Published", Toast.LENGTH_LONG).show();
title.setText("");
des.setText("");
image.setImageURI(null);
imageuri = null;
startActivity(new Intent(PostBlogActivity.this, DashboardActivity.class));
PostBlogActivity.this.finish();
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(PostBlogActivity.this, "Failed", Toast.LENGTH_LONG).show();
}
});
}
I've copied what the tutorial says inside of android studio however that doesn't work, I am using the free version right now however that shouldn't stop me from writing to the database. It gives no errors or warnings that what I have done is wrong so that it would upload to the Realtime database instead. I have read my code to see if I have referenced the Realtime database by mistake however that piece of code is all what accesses and writes to the database. Though if my code was wrong I would expect it to crash and not upload the data to another database.
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 developed a code to upload an image to the firebase.
In consultation the firebase storage I found that the image is well uplode.
To retrieve the downloadUrl I used a Listener but it seems to me that the Listener does not work.
mFirebaseStorage = FirebaseStorage.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
mProductStorageReference = mFirebaseStorage.getReference().child("images");
mPostsDatabaseReference = mFirebaseDatabase.getReference().child("posts");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
File f = new File(imagePath);
bitmap = BitmapFactory.decodeFile(f.getPath());
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, bytes);
String path = MediaStore.Images.Media.insertImage(PostNewProductActivity.this.getContentResolver(),
bitmap, imagePath, null);
Uri uri = Uri.parse(path);
// Upload file to Firebase Storage
final String finalAdress = adress;
final double finalMyLat = MyLat;
final double finalMyLong = MyLong;
StorageReference photoRef = mProductStorageReference.child(uri.getLastPathSegment());
photoRef.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.i("tag", "onSuccess");
// When the image has successfully uploaded, we get its download URL
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
Product product = new Product(userName, mLastUpdateTime, finalAdress, finalMyLat, finalMyLong,
descriptionUser.getText().toString(), descriptionApi, downloadUrl.toString(), price.getText().toString());
mPostsDatabaseReference.push().setValue(product);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Log.i("tag", "onFailure");
}
});
I consulted the log I didn't find -onSuccess tag- and -onFailure tag-, although the photo is well in firebase
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
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) + "%...");
}
});
}
}
}