Display Image from Database with userID in ImageView (Android SDK) [duplicate] - android

This question already has answers here:
How to display image from URL on Android
(10 answers)
Closed 4 years ago.
Heyho,
currently im working on my Firebase Database (android sdk). I managed to upload the image to the storage and save the url in my database (under the user ID).
Now im really out of ideas how to display the image from the database into a imageView.
Probably you already understand that im trying create some type of "profile picture".
Btw. is would be really nice if someone can help me without using Glide. If Glide is needed i will get Glide then instead.
Thank you all for reading my question and helping me!
Database Image

Firstly you can put an image using an url by using:
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
If you use the Firebase storage why don't you just download the file directly from there?
StorageReference mStorageRef = FirebaseStorage.getInstance().getReference();
StorageReference riversRef = mStorageRef.child("images/name.jpg");
File localFile = null;
try {
localFile = File.createTempFile("images", "jpg");
} catch(IOException e) {
e.printStackTrace();
}
riversRef.getFile(localFile)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// Successfully downloaded data to local file
// ...
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle failed download
// ...
}
});
If you do need to use the url then you will need to use an AsyncTask to get the image.

Related

Why can't this retieve the download URL of an image on Firebase Storage?

I am trying to retrieve an image from firebase storage for an android app by getting the download url of the image I want to retrieve in the onSuccessListener of the putImage call I used to upload the image in the first place. I am saving the download URL in a field variable but the issue is that the field variable is not being updated. I used toast to print out the value of the url field variable after my attempt in setting it equal to the download URl of the image I want to retrieve, but it remains unchanged. I'm not sure why this is the case so I would appreciate any help in resolving this.
//field variable that s meant to hold download url for the image I want to retrieve
String url = "never changed"
...
final String imageKey = UUID.randomUUID().toString();
StorageReference profileref = storageReference.child("contactProfiles/" + imageKey);
profileref.putFile(imageUri).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) {
//setting url equal to url of the image I want to retrieve
url = uri.toString();
}
});
Toast.makeText(ContactCreation.this, "Successful Profile Picture Upload", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ContactCreation.this, "Failed to Upload Profile Picture", Toast.LENGTH_SHORT).show();
}
});
//Seeing if the url changed or not
Toast.makeText(ContactCreation.this, url, Toast.LENGTH_SHORT).show();
The call to getDownloadURL makes a call to the server, and thus is executed asynchronously. This means that right now in your code, the Toast.makeText(ContactCreation.this, url runs before the url = uri.toString() ever runs, which explains why it logs no value.
The solution is always the same: any code that needs the value, needs to be inside the onSuccess that is called with the value, or it needs to be called from there.
So:
task.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
url = uri.toString();
Toast.makeText(ContactCreation.this, url, Toast.LENGTH_SHORT).show();
}
});
If you're new to such asynchronous behavior, I recommend reading some more about it. For example with:
URL generated by Firebase Storage does not allow access to the file, which shows some chaining of Task listeners.
How to get the download url from Firebase Storage?
Hello, I have problem to upload my image to my firebase storage

App crashes and giving "java.lang.NullPointerException" error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have already seen many questions in stackoverflow but none of them able to solve my problem. Here is my code.There is no error in code but app is crashing at runtime giving this error in Logcat - Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
public void SaveImageInFirebase(){
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://opiniondonkey-9c20e.appspot.com");
SimpleDateFormat df = new SimpleDateFormat("ddMMyyHHmmss");
Date dataobj = new Date();
String imagePath = df.format(dataobj) + ".jpg";
StorageReference ImageRef = storageRef.child("images/" + imagePath);
mPic.setDrawingCacheEnabled(true);
mPic.buildDrawingCache();
Drawable drawable = mPic.getDrawable();
//TODO:: error in below line.
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = ImageRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Welcome To Opinion Donkey",Toast.LENGTH_LONG).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getStorage().getDownloadUrl();
myRef.child("Users").child(name).child("ProfileUrl").setValue(downloadUrl);
}
});
}
I want when someone logins again then google id picture should not overrides over my user picture.
May be mPic.getDrawable(); is returning null. so drawable is null and you are accessing it by ((BitmapDrawable)drawable).getBitmap();
It might be because Picasso loads image in ImageView async and you are trying to access that before it is loaded/downloaded.
so mPic.getDrawable() returns null.
Add check before accessing if(drawable != null) there.
Also, this needs to be called only after Picasso done with it's loading. so you can add listener there and access image only after it is done loading.

How to get all files from firebase storage?

I have uploaded some files into Firebase directory and I want to list them and download one by one.There is no API/Documentation fo this.Could you help me ?
As of July 2019, version 18.1.0 of the Cloud Storage SDK now supports listing all objects from a bucket. You simply need to call listAll() in a StorageReference:
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
// Now we get the references of these images
storageRef.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(ListResult result) {
for(StorageReference fileRef : result.getItems()) {
// TODO: Download the file using its reference (fileRef)
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception exception) {
// Handle any errors
}
});
If you want to download these files, you can use one of the options shown in the Docs.
Please note that in order to use this method, you must opt-in to version 2 of Security Rules, which can be done by making rules_version = '2'; the first line of your security rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
first , you should get the file download Url to retrieve it, the easiest way is to upload a file and generate the download Url in your database, so after that you just go and retrieve each file from the storage like this :
private void downloadFile() {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("<your_bucket>");
StorageReference islandRef = storageRef.child("file.txt");
File rootPath = new File(Environment.getExternalStorageDirectory(), "file_name");
if(!rootPath.exists()) {
rootPath.mkdirs();
}
final File localFile = new File(rootPath,"imageName.txt");
islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.e("firebase ",";local tem file created created " +localFile.toString());
// updateDb(timestamp,localFile.toString(),position);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.e("firebase ",";local tem file not created created " +exception.toString());
}
});
}
I personally use this method, whenever you upload a file, save its download URL in your Firebase Database, if you are uploading multiple files then save it in an array. There is no method for Firebase Storage android to download and upload multiple files in one go.
Whenever you want to download files access your firebase database for those URL's.

Image from StorageReference Firebase-Android

TextView myUsername=(TextView) findViewById(R.id.user);
myProfile=(ImageView) findViewById(R.id.photo);
Bundle bundleObject=getIntent().getExtras();
myAccount=(Account) bundleObject.getSerializable("account");
myUsername.setText(myAccount.get_username());
StorageReference profile =
FirebaseStorage.getInstance()
.getReference().child("profiles").child(myAccount.getUID()).child("profile");
profile.getDownloadUrl().addOnSuccessListener(Profile.this, new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
myProfile.setImageURI(uri);
}
});
I'm trying to put the image from the Firebase Storage in the ImageView but is not showing and I don't have any error . What I'm doing wrong?
ImageView doesn't load images from the internet itself - and the URL retrieved from Storage is a regular HTTPS one. The setImageURI method is for loading from the local file system.
You can use a library like Glide or Picasso to do the image loading - if you take a look at FirebaseUI, you'll find a helpful integration that includes caching: https://github.com/firebase/FirebaseUI-Android/tree/master/storage

Android FireBase error when uploading picture

I am trying to upload a picture via a local file method.
UploadTask uploadTask = currentPicRef.putFile(file, metadata);
When the user pick's image from the gallery or taking a picture via the camera the picture is saved in external storage and I save the uri in shared preference.
I successfully loaded the image into an imageview using the setImageURI(uri) method, but When I call the firebase method and using the same uri (Uri file = Uri.fromFile(new File(fileName));)
I get the error
could not locate file for uploading:file:///content%3A/media/external/images/media/22943
but when I use log to check the local file I get
uri is content://media/external/images/media/22943
also worth to mention that when I used uri.parse() instead uri.fromFile() in firebase to upload from a local file it uploaded the metadata but not the photo itself.
Any ideas how to fix it?
Maybe it's a bit late, anyway:
could not locate file for uploading:file:///content%3A/media/external/images/media/22943
I think you may have a problem of url encoding (see %3A in the file uri).
Try to decode the uri Uri file = Uri.fromFile(new File(fileName)); before passing it to Firebase Storage Reference.
If it does not work, instead retrieving the image uri in this way Uri.fromFile(new File(fileName)) , you can try to save the local image path in the shared preferences (I'm supposing that when you get the image from gallery or camera, you can have also the local path), and use this to upload the image in the storage Firebase.
Hope can help.
fileName can be determined fileUri.toString(). This worked for me:
Uri uploadUri = Uri.fromFile(new File(fileUri.toString()));
Here's an example that works:
// [START upload_from_uri]
private void uploadFromUri(Uri fileUri) {
Uri uploadUri = Uri.fromFile(new File(fileUri.toString()));
Log.d(TAG, "uploadFromUri:src:" + fileUri.toString());
// [START get_child_ref]
// Get a reference to store file at photos/<FILENAME>.jpg
final StorageReference photoRef = mStorageRef.child("photos").child(uploadUri.getLastPathSegment());
// [END get_child_ref]
// Upload file to Firebase Storage
// [START_EXCLUDE]
showProgressDialog();
// [END_EXCLUDE]
Log.d(TAG, "uploadFromUri:dst:" + photoRef.getPath());
photoRef.putFile(uploadUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Upload succeeded
Log.d(TAG, "uploadFromUri:onSuccess");
// Get the public download URL
mDownloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
// [START_EXCLUDE]
hideProgressDialog();
updateUI(mAuth.getCurrentUser());
// [END_EXCLUDE]
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Upload failed
Log.w(TAG, "uploadFromUri:onFailure", exception);
mDownloadUrl = null;
// [START_EXCLUDE]
hideProgressDialog();
Toast.makeText(MainActivity.this, "Error: upload failed",
Toast.LENGTH_SHORT).show();
updateUI(mAuth.getCurrentUser());
// [END_EXCLUDE]
}
});
}
// [END upload_from_uri]

Categories

Resources