Can't get image from firebase storage using glide library - android

i'm trying to get profile picture for every user from firebase storage within a firestore recycler adapter. i'm using the glide library to load the picture on the imageview. But i'm getting a StorageException. I always used the same code before to get picture from Firebase Storage but now i don't know what does changed.
Here's my code:
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder usersViewHolder, int i, #NonNull User user) {
FirestoreUsage.getUserPictureReference(user.getMail(), user.getGender()).child("profile_picture.jpg").getDownloadUrl()
.addOnSuccessListener(uri -> Glide.with(context).load(uri)
.into(usersViewHolder.image));
usersViewHolder.name.setText(user.getName());
usersViewHolder.city.setText(user.getCity());
}
// ONE USER STORAGE REFERENCE
public static StorageReference getUserPictureReference(String userMail, String gender) {
return getAllUsersStorageRef().child(gender).child(userMail).child("PROFILE PICTURE");
}
And here is the exception:
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", "status": "GET_OBJECT" }}
java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
at com.google.firebase.storage.network.NetworkRequest.parseResponse(NetworkRequest.java:434)
at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(NetworkRequest.java:451)
at com.google.firebase.storage.network.NetworkRequest.processResponseStream(NetworkRequest.java:442)
at com.google.firebase.storage.network.NetworkRequest.performRequest(NetworkRequest.java:272)
at com.google.firebase.storage.network.NetworkRequest.performRequest(NetworkRequest.java:286)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(ExponentialBackoffSender.java:70)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(ExponentialBackoffSender.java:62)
at com.google.firebase.storage.GetDownloadUrlTask.run(GetDownloadUrlTask.java:76)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
Please help me

I have found a solution for my problem. It was about path.
Earlier, when i was registrating the profil picture of the user in firebase storage, i also saved the path of the picture in firestore.
StorageReference userProfilePicture = FirestoreUsage.getUserPictureReference(Prevalent.currentUserOnline.getMail(), gender).child("profile_picture.jpg");
userProfilePicture.putFile(uriImageSelected).addOnSuccessListener(this, taskSnapshot -> {
String pathImageSavedInFirebaseStorage = Objects.requireNonNull(taskSnapshot.getMetadata()).getPath();
choiceMap.put("profile_picture", pathImageSavedInFirebaseStorage);
Prevalent.currentUserOnline.setProfile_picture(pathImageSavedInFirebaseStorage);
Then in my adapter, i created a Storage Reference with that path and dowloaded the pic
StorageReference storageReference = FirebaseStorage.getInstance().getReference(user.getProfile_picture());
storageReference.getDownloadUrl().addOnSuccessListener(uri -> Glide.with(context).load(uri)
.into(usersViewHolder.image));

Related

Flutter Fire - [Firebase Storage] W/NetworkRequest( 5624): no auth token for request

My flutter app has a download feature that displays pdf from firebase storage and a download button to download the file. The view pdf function is working fine. However, the download pdf throws an exception
W/StorageUtil( 5624): no auth token for request
D/EGL_emulation( 5624): app_time_stats: avg=107.69ms min=6.46ms max=1118.11ms count=13
W/StorageUtil( 5624): Error getting App Check token; using placeholder token instead. Error: com.google.firebase.FirebaseException: Too many attempts.
E/StorageException( 5624): An unknown error occurred, please check the HTTP result code and inner exception for server response.
E/StorageException( 5624): User does not have permission to access this object.
E/StorageException( 5624): Code: -13021 HttpResult: 403
E/StorageException( 5624): { "error": { "code": 403, "message": "Permission denied." }}
Details about the app:-
The App does not have authentication (Feature not required so far)
The storage rules in firebase storage is open to all users.
match /documents/{docId}{allow read,write;}
App check not enabled or enforced. All requests are allowed to the storage bucket so far.
The sample code that I am trying to download the file is
Future<void> downloadFile(String downloadUrl, String filename) async {
Directory appDocDir = await getApplicationDocumentsDirectory();
File downloadToFile = File('${appDocDir.path}/$filename');
try {
var url = await firebase_storage.FirebaseStorage.instance
.ref('documents/$filename')
.storage
.ref();
await url.writeToFile(downloadToFile);
} on firebase_core.FirebaseException catch (e) {
print('Exception' + e);
}
}
I have updated all the packages & dependencies but in vain. I am sure that I am missing something. A helping hand will be greatly appreciated.
Try:
final isRef = await firebase_storage.FirebaseStorage.instance
.ref().child("'documents/$filename'");
Directory appDocDir = await getApplicationDocumentsDirectory();
File downloadToFile = File('${appDocDir.path}/$filename');
final downloadTask = isRef.writeToFile(downloadToFile);

Retrieving image from Firebase Storage

I know this is a discussed topic, but here I am, after all other solutions I've found did not solve my problem. I saved multiple images in Firebase Storage and now I want to get one of them and put it into an ImageView on an AlertDialog (or another Activity).
I've read about Glide solution, but it doesn't work for me. Gilde:
Glide.with(ViewScenesSG.this) //ViewScenesSG is the Activity
.load(reference) //the storage reference
.into(imageView); //my imageView
Dependencies for Glide (I've tried with multiple versions and 4.8.0 is the only one that doesn't give me Build error):
implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
annotationProcessor 'androidx.annotation:annotation:1.1.0'
I've also read about the .using(new FirebaseImageLoader()) method, I've implemented the FirebaseImageLoader(), but the using() method is not found => build error. I believe it's been removed.
The second version I've tried is this one (found in another question here):
final long ONE_MEGABYTE = 1024 * 1024;
reference.getBytes(ONE_MEGABYTE)
.addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
Bitmap bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
imageView.setMinimumHeight(dm.heightPixels);
imageView.setMinimumWidth(dm.widthPixels);
imageView.setImageBitmap(bm);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(ViewScenesSG.this, "Couldn't retrieve image.", Toast.LENGTH_SHORT).show();
}
});
But every time it goes on the Failure listener. Therefore, my imageView always remains empty.
In my logcat I observed this error:
E/StorageException: Could not open resulting stream.
java.io.IOException: Could not open resulting stream.
at com.google.firebase.storage.StreamDownloadTask.createDownloadStream(com.google.firebase:firebase-storage##19.1.1:145)
at com.google.firebase.storage.StreamDownloadTask.access$000(com.google.firebase:firebase-storage##19.1.1:36)
at com.google.firebase.storage.StreamDownloadTask$1.call(com.google.firebase:firebase-storage##19.1.1:167)
at com.google.firebase.storage.StreamDownloadTask$1.call(com.google.firebase:firebase-storage##19.1.1:164)
at com.google.firebase.storage.StreamDownloadTask$StreamProgressWrapper.ensureStream(com.google.firebase:firebase-storage##19.1.1:325)
at com.google.firebase.storage.StreamDownloadTask$StreamProgressWrapper.access$100(com.google.firebase:firebase-storage##19.1.1:262)
at com.google.firebase.storage.StreamDownloadTask.run(com.google.firebase:firebase-storage##19.1.1:175)
at com.google.firebase.storage.StorageTask.lambda$getRunnable$7(com.google.firebase:firebase-storage##19.1.1:1072)
at com.google.firebase.storage.StorageTask$$Lambda$12.run(Unknown Source:2)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
E/StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
But the image is there, in the Storage, and the reference points directly to it:
storageRef = storage.getReference("photos").child(title); //for all images in the current folder named with the 'title' attribute
StorageReference reference = storageRef.child(imageName); //for the image I want to retrieve
What am I missing?
EDIT: Using the suggestion in the coments, I tried with:
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Glide.with(ViewScenesSG.this)
.load(uri.toString())
.into(imageView);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ViewScenesSG.this, "Retrieving image failed",
Toast.LENGTH_SHORT).show();
}
});
but this time I get the error:
E/StorageException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
at com.google.firebase.storage.network.NetworkRequest.parseResponse(com.google.firebase:firebase-storage##19.1.1:433)
at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(com.google.firebase:firebase-storage##19.1.1:450)
at com.google.firebase.storage.network.NetworkRequest.processResponseStream(com.google.firebase:firebase-storage##19.1.1:441)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##19.1.1:272)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##19.1.1:286)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##19.1.1:70)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##19.1.1:62)
at com.google.firebase.storage.GetDownloadUrlTask.run(com.google.firebase:firebase-storage##19.1.1:76)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
I found the following solution (as suggested in the comments before):
Using the Firebase UI plugin with Gilde, I added the following dependency:
implementation 'com.firebaseui:firebase-ui-storage:6.2.0'
Now, having the StorageReference reference pointing to the image, and the ImageView in which the content must be uploaded, the following code retrieves the image and puts it in the ImageView:
Glide.with(ViewScenesSG.this) //this is the current Activity
.load(reference)
.into(imageView);
To be mentioned that the ImageView must have the dimensions set to a specific value, not using wrap_content or match_parent (at least for height in my case), otherwise it will appear as a small icon. This can also depend on how the image was saved before in the Storage.
Hope this will help someone else as well!
I'm not sure what's going wrong in your second snippet, but in the first snippet you seem to be passing a StorageReference to Glide. Since Glide doesn't know anything about Firebase Storage, that won't work.
Instead, you should get a download URL from Firebase Storage, which is a regular HTTPS URL that provides public access to the data, and pass that to Glide to render in the view.
Something like:
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'users/me/profile.png'
Glide.with(ViewScenesSG.this)
.load(uri.toString())
.into(imageView);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});

Get Image Download url by Passing Firebase Storage Reference [duplicate]

This question already has answers here:
How to get URL from Firebase Storage getDownloadURL
(13 answers)
Closed 3 years ago.
Is it Possible to get Download uri by using Firebase Storage Reference ?
This is question not similar to this question
Above question problem was get image url by uploading image.
I want to try something get Image Download URI by providing Image Ref from Storage.
I tried something :
storageReference.child("images/download.jpg").downloadUrl.addOnSuccessListener { uri ->
if (uri != null){
Log.e("url", uri.toString())
}
}
Image :
It shows Error (i know something like that does not exist) :
E/StorageException: { "error": { "code": 404, "message": "Not
Found. Could not get object", "status": "GET_OBJECT" }}
java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
at com.google.firebase.storage.network.NetworkRequest.parseResponse(com.google.firebase:firebase-storage##17.0.0:455)
at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(com.google.firebase:firebase-storage##17.0.0:435)
at com.google.firebase.storage.network.NetworkRequest.processResponseStream(com.google.firebase:firebase-storage##17.0.0:426)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##17.0.0:280)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##17.0.0:294)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##17.0.0:70)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##17.0.0:62)
at com.google.firebase.storage.GetDownloadUrlTask.run(com.google.firebase:firebase-storage##17.0.0:74)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
I am just looking for show image without using glide library. so i am looking for image uri to show image.
Try this:
StorageReference storageReference = FirebaseStorage.getInstance().getReferenceFromUrl("storage ref url in string");
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//do your stuff- uri.toString() will give you download URL\\
}
});
or directly use StorageReference if you already initialized it.

Firebase Bucketname Not Available

I'm having a weird problem with Firebase in Android. I'm trying to upload a photo to Firebase Storage and I'm getting the following error:
E/UncaughtException: java.lang.IllegalArgumentException: The supplied bucketname is not available to this project.
At this line of code:
StorageReference mStorageRef = mFirebaseStorage.getReferenceFromUrl("gs://mooseandroid-a9f96.appspot.com");
I'm sure that the bucketname is the same as the one in the console. I even tried with a bucketname that works fine in iOS with Swift. I also changed the rules to public so anyone can read and write to this storage bucket. The realtime database works fine for this project. I'm running out of options right now, don't even know what else I could be trying.
Here's the whole piece of code:
FirebaseStorage mFirebaseStorage = FirebaseStorage.getInstance();
StorageReference mStorageRef = mFirebaseStorage.getReferenceFromUrl("gs://mooseandroid-a9f96.appspot.com");
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.
});
And here's the whole error:
E/UncaughtException: java.lang.IllegalArgumentException: The supplied bucketname is not available to this project.
at com.google.android.gms.common.internal.zzaa.zzb(Unknown Source)
at com.google.firebase.storage.FirebaseStorage.zzz(Unknown Source)
at com.google.firebase.storage.FirebaseStorage.getReferenceFromUrl(Unknown Source)
at com.moose.android.AddPostActivity.onClick(AddPostActivity.java:163)
at android.view.View.performClick(View.java:5702)
at android.widget.TextView.performClick(TextView.java:10888)
at android.view.View$PerformClick.run(View.java:22541)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
The documentation for getReferenceFromUrl(String fullUrl) states:
An error is thrown if fullUrl is not associated with the FirebaseApp
used to initialize this FirebaseStorage
Use this code to see the bucket name in your FirebaseApp:
FirebaseOptions opts = FirebaseApp.getInstance().getOptions();
Log.i(TAG, "Bucket = " + opts.getStorageBucket());
I expect it will not be mooseandroid-a9f96.appspot.com and will instead be the storage_bucket value in the project_info section of your google-services.json file:
"project_info": {
"project_number": "816275527980",
"firebase_url": "https://project-8693710910123456789.firebaseio.com",
"project_id": "project-8693710910123456789",
"storage_bucket": "project-8693710910123456789.appspot.com"
},
If anyone changes the bucket url afterwards just clean and rebuild the android project, it solved the issue for me.
For cleaning go to Build tab on top nav bar in android studio -> Click Clean Project.
For rebuilding again go to Build tab on top nav bar in android studio -> Click Rebuild Project.

Object Not Fount Exception when I am trying to set FirebaseStorage Image file in ImageView in Android

I am developing an app where I want to display uploaded image from firebase storage by setting it to an Imageview using url. I am using following code to get this done.
StorageReference storageReference = FirebaseStorage.getInstance().getReference("ImageFolder/"+imageId);
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.with(getContext()).load(uri).into(viewHolder.imageThumbnail);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
This throws an Exception as following
StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
08-09 22:50:05.280 10915-11000/com.app.myapp 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 bxr.a(:com.google.android.gms.DynamiteModulesC:424)
at bxr.a(:com.google.android.gms.DynamiteModulesC:1404)
at bxl.onTransact(:com.google.android.gms.DynamiteModulesC:53)
at android.os.Binder.transact(Binder.java:387)
at com.google.android.gms.internal.zzamj$zza$zza.zzss(Unknown Source)
at com.google.android.gms.internal.zzamm.zza(Unknown Source)
at com.google.android.gms.internal.zzamd.zza(Unknown Source)
Please help with the issue.
I have a same issues , in my app i was saving URL in Database and image in Storage.
just Clean entire STORAGE and DATABASE thing and its works well in my case.
or
i found it why its happen..
it returns non-null firebase.Promise containing string A Promise that resolves with the download URL or rejects if the fetch failed, including if the object did not exist.
Check here for this method getDownloadURL()
This occurs when there is not an item in firebase storage at the specified location.
Here is what the exception looks like in Android:
04-13 07:07:48.851 20923-22411/org.emeritus.globalivy 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 bti.a(:com.google.android.gms.DynamiteModulesC:428)
at bti.a(:com.google.android.gms.DynamiteModulesC:1408)
at btc.onTransact(:com.google.android.gms.DynamiteModulesC:53)
at android.os.Binder.transact(Binder.java:380)
at com.google.android.gms.internal.zzbub$zza$zza.zzjM(Unknown Source)
at com.google.android.gms.internal.zzbue.zzd(Unknown Source)
at com.google.android.gms.internal.zzbtv.zza(Unknown Source)
at com.google.android.gms.internal.zzbtv.zze(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)
It would be nice if the Firebase SDK didn't output the entire stacktrace to the logs and only this
StorageException has occurred.
Object does not exist at location.

Categories

Resources