I am working on an app where I have uploaded images to Firebase, then I use a query to look for an image based on its name, I display it in an imageview, then I try to upload this image to a different table in the same firebase database.
My problem is that when I try to upload the image to the other table, I get a No content provider error, and in front of it is a fully working link to my image (I click on it and my image is displayed in the browser).
Here is the code that I have tried :
private void addToMenu(){
final Query query = mDatabaseRef.orderByChild("name").equalTo(EditTextName.getText().toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot NamedImage : dataSnapshot.getChildren()) {
SliderUtils sliderUtils = NamedImage.getValue(SliderUtils.class);
Uri uriFile = Uri.parse(sliderUtils.getImageUrl());
StorageReference Ref= menuStorageRef.child(System.currentTimeMillis()+"."+getPath(uriFile));
mStorageTask = Ref.putFile(uriFile)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Image uploaded successfully.",
Toast.LENGTH_LONG).show();
SliderUtils sliderUtils = new SliderUtils(EditTextName.getText().toString().trim(),
taskSnapshot.getDownloadUrl().toString());
String uploadId = menuDatabaseRef.push().getKey();
menuDatabaseRef.child(uploadId).setValue(sliderUtils);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(MainActivity.this,"Image upload failed.",Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
});
}
}
}
the getPath() function is the following:
private String getPath(Uri uri){
ContentResolver cr = getContentResolver();
MimeTypeMap mimeTypeMap= MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
The error I get is :
/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
E/StorageException: No content provider: https://firebase...
Do you have any idea where the problem is please?
for anyone in the same situation and looking for a solution:
A big mistake that I had is that I was trying to turn an URL into a URI which is simply impossible
So I decided to change the way that I was uploading my image altogether. Here is the code:
private void addToMenu(){
final Query query =
mDatabaseRef.orderByChild("name").equalTo(EditTextName.getText().toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot NamedImage : dataSnapshot.getChildren()) {
SliderUtils sliderUtils = NamedImage.getValue(SliderUtils.class);
StorageReference Ref= menuStorageRef.child("filename" + new Date().getTime());
image.setDrawingCacheEnabled(true);
image.buildDrawingCache();
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = Ref.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(MainActivity.this,"Image upload failed.",Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Image uploaded successfully.", Toast.LENGTH_LONG).show();
SliderUtils sliderUtils = new SliderUtils(EditTextName.getText().toString().trim(),
taskSnapshot.getDownloadUrl().toString());
String uploadId = menuDatabaseRef.push().getKey();
menuDatabaseRef.child(uploadId).setValue(sliderUtils);
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Related
hi every one am making an app that use firebaseDatabase for Users info and firebaseStorage to save the image and i want to put the path of the image uploaded to firebaseStorage in firebaseDatabase under User info so i can display the image like profile pic so am using this to upload image and mainActivity to show the image . i do search for solution and got some but it didnt work or i didnt know how to make it work . am new at android
upload image
public String getExtension(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getMimeTypeFromExtension(contentResolver.getType(uri));
}
private void uploadImage() {
StorageReference reference = mStorage.child(System.currentTimeMillis()+"."+getExtension(imageUri));
uploadTask= reference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
// Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(AddImageActivity.this,"Image Uploaded",Toast.LENGTH_SHORT).show();
Intent ii = new Intent(AddImageActivity.this,MainActivity.class);
startActivity(ii);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
MainActvity
public class MainActivity extends AppCompatActivity {
ImageView profilePic ;
TextView nameProfile ;
DatabaseReference databaseReference ;
FirebaseUser fUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
profilePic=findViewById(R.id.imageProfile);
nameProfile = findViewById(R.id.nameProfile);
fUser=FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(fUser.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
nameProfile.setText(user.getName());
Glide.with(getApplicationContext()).load(user.getImageURL()).into(profilePic);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
that work for me
final StorageReference reference = mStorageReference.child(System.currentTimeMillis() + "." + getExtension(imageUri));
reference.putFile(imageUri).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 imageUrl = uri.toString();
}
}
);
}
});
public void uploadfile(){
if(uri!=null){
final StorageReference filereference=storageReference.child(System.currentTimeMillis()+"."+getFileExtension(uri));
filereference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
filereference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Upload upload=new Upload(editText1.getText().toString(),uri.toString());
String str=databaseReference.push().getKey();
databaseReference.child(str).setValue(upload);
progressBar.setVisibility(View.INVISIBLE);
progressBar2.setVisibility(View.VISIBLE);
final Timer timer=new Timer();
TimerTask timerTask=new TimerTask() {
#Override
public void run() {
counter++;
progressBar2.setProgress(counter);
if (counter==100){
toast.show();
progressBar2.setVisibility(View.INVISIBLE);
counter=0;
timer.cancel();
}
}
};timer.schedule(timerTask,1,15);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
Hello my friend please copy-paste your function like this
private void uploadImage() {
StorageReference reference = mStorage.child(System.currentTimeMillis()+"."+getExtension(imageUri));
uploadTask= reference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String uploadedImageUrl = uri.toString();
// Now you have your image in (uploadedImageUrl) variable so write your code to upload in firebaseDatabase and enjoy
}
});
Toast.makeText(AddImageActivity.this,"Image Uploaded",Toast.LENGTH_SHORT).show();
Intent ii = new Intent(AddImageActivity.this,MainActivity.class);
startActivity(ii);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
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'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) + "%...");
}
});
}
}
}
Im' using FirebaseUI with Recycler View and load images from Firebase Storage. I got an error above when I'm trying to replace the image with another one.
When I exit the fragment and back again, the image shows up, the error occurs in the same fragment where I'm changing the image.
I tried to use adapter.wait() and adapter.notifyDataSetChanged() but still get that error. The full error is this:
E/StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
E/StorageException: { "error": { "code": 404, "message": "Not Found. Could not get object" }}
java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not get object" }}
at bvk.a(:com.google.android.gms.DynamiteModulesC:424)
at bvk.a(:com.google.android.gms.DynamiteModulesC:1404)
at bve.onTransact(:com.google.android.gms.DynamiteModulesC:53)
at android.os.Binder.transact(Binder.java:380)
at com.google.android.gms.internal.zzans$zza$zza.zzuj(Unknown Source)
at com.google.android.gms.internal.zzanv.zza(Unknown Source)
at com.google.android.gms.internal.zzanm.zza(Unknown Source)
at com.google.android.gms.internal.zzanm.zzd(Unknown Source)
at com.google.firebase.storage.zzb.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
And my code is this:
protected void populateViewHolder(final ReportViewHolder viewHolder, final Report report, final int position) {
viewHolder.txtTitle.setText(report.title);
viewHolder.txtMessage.setText(report.message);
viewHolder.txtDate.setText(report.date);
viewHolder.txtuserName.setText(report.userName);
viewHolder.btnImg.setImageBitmap(null);
mStorage.child("Images/" + report.key + "/" + report.imageName).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.with(getContext()).load(uri).into(viewHolder.btnImg);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Title=title.getText().toString();//get text from EditText
final String msg= message.getText().toString();
Query query= mDatabaseReference.child("user-reports/"+userID).orderByKey().equalTo(report.key);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot: dataSnapshot.getChildren())
{
snapshot.getRef().setValue(new Report(report.userName,report.date, Title, msg, report.key,
targetUri.getLastPathSegment()));
update_img(report.key, report.imageName);
mDatabaseReference.child("reports/"+ report.key).setValue(new Report(report.userName,report.date, Title, msg, report.key,
targetUri.getLastPathSegment()));
dialog.dismiss();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
And the function to update is this:
public void update_img(String key, String imageName)
{
// Get the data from an ImageView as bytes
imgView.setDrawingCacheEnabled(true);
imgView.buildDrawingCache();
Bitmap bitmap = imgView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data2 = baos.toByteArray();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setCancelable(false);
final View view = inflater.inflate(R.layout.progbar, null);
builder.setView(view);
TextView progTitle = (TextView) view.findViewById(R.id.progTitle);
progTitle.setText("wait to update");
final Dialog progDialog = builder.create();
progDialog.show();
if(targetUri != null) {
mStorage.child("Images/" + key + "/" + imageName).delete(); // Delete the old image of the user
StorageReference filepathRef = mStorage.child("Images/"+ key).child(targetUri.getLastPathSegment()); // Add the new image of the user
UploadTask uploadTask = filepathRef.putBytes(data2);
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) {
progDialog.cancel();
Toast.makeText(getContext(), "success", Toast.LENGTH_SHORT).show();
}
});
}
}
Hope you know what to do, because I really don't know what else I can do.