Unable to fetch file from firebase storage - java

I am unable to fetch the uploaded image file from the firebase storage because the database stores the url in a public unguessable url form and I cannot seem to figure it out, what is wrong with my code?
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setAspectRatio(1,1)
.start(this);
//Toast.makeText(SettingsActivity.this, imageUri, Toast.LENGTH_LONG).show();
}
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
mProgressDialog = new ProgressDialog(SettingsActivity.this);
mProgressDialog.setTitle("Uploading");
mProgressDialog.setMessage("Please Wait While The Image Is Being Uploaded");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
String current_user_id = mCurrentUser.getUid();
StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
final String download_url = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
mUserDatabase.child("image").setValue(download_url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
mProgressDialog.dismiss();
Toast.makeText(SettingsActivity.this, "Uploaded Successfully", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
});
} else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
Exception error = result.getError();
}
}
}

First you can convert your image in bitmap stream and then you can upload it on firebase storage and get downloadable link also easily. You can do something like this below:
StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,40,baos);
byte[] byt = baos.toByteArray();
UploadTask uploadTask = filepath.putBytes(byt);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
TastyToast.makeText(getApplicationContext(),"Error:"+e.getMessage(),TastyToast.LENGTH_LONG,
TastyToast.ERROR).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if(taskSnapshot.getMetadata() != null){
Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
downloadUrl = Uri.parse(uri.toString());
// In downloadUri variable you will get your
image downloadable link
}
});
}
}
});

Related

Cannot upload the image to firebase

I am trying to upload the image using firebase but I am not able to do so. I am not getting what is going wrong while uploading. Here is the code:
private void saveUserInformation() {
mCustomerDatabase.updateChildren(userInfo);
if (resultUri != null) {
final StorageReference filepath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
assert bitmap != null;
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = filepath.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("SA", "Fail1");
finish();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map newImage = new HashMap();
newImage.put("profileImageUrl", uri.toString());
mCustomerDatabase.updateChildren(newImage);
Log.d("SA", "Success");
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.e("SA", "Fail2");
finish();
}
});
}
});
} else {
finish();
}
}
The StorageException occurs and it is not uploaded in the firebase console as well. Help appreciated!!
Define Variable
private static int GALLERY_PICK = 1 ;
private Uri imageUri;
private Button uploudBtn;
private ImageView profileImageView;
imageView, when pressed, chooses the image from the gallery.
profileImageView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent , GALLERY_PICK);
}
});
onActivityResult method.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK && data != null)
{
imageUri = data.getData();
profileImageView.setImageURI(imageUri);
}
}
and then the upload code for image(button )
uploudBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(imageUri != null)
{
final StorageReference filePath = userProfileImageRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
final UploadTask uploadTask = filePath.putFile(imageUri);
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();
}
downloadUrl = filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>()
{
#Override
public void onComplete(#NonNull Task<Uri> task)
{
if (task.isSuccessful())
{
downloadUrl = task.getResult().toString();
Toast.makeText(MainActivity.this, "Your profile Info has been updated", Toast.LENGTH_SHORT).show();
}
}
});
**Remark you should cast uploudBtn , profileImageView in OnCreate methods **
profileImageView = findViewById(R.id.imageView);
uploudBtn = findViewById(R.id.button);

Retrieve image download url from Firebase Storage [duplicate]

This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
How to get URL from Firebase Storage getDownloadURL
(13 answers)
Closed 2 years ago.
I am trying to retrieve an image from my firebase storage but I'm having problems storing the image download url. I am using final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString(); but this is only reutrning a reference to the task I believe - com.google.android.gms.tasks.zzu#add13a0
What I want to be storing/retrieving is https://firebasestorage.googleapis.com/v0/b/chat-poll-application.appspot.com/o/Group%20Images%2FGig.jpg?alt=media&token=9a90fc94-e65f-4ace-9259-aaaa91b449c3
Can anyone see where I'm going wrong?
Here is the full code:
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Toast.makeText(GroupSettingsActivity.this, "Group image uploaded successfully", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
RootRef.child("Groups").child(currentGroupName).child("Image").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(GroupSettingsActivity.this, "Image saved successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
String message = task.getException().toString();
Toast.makeText(GroupSettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).toString();
loadingBar.dismiss();
}
}
});
} else {
String message = task.getException().toString();
Toast.makeText(GroupSettingsActivity.this, "Error " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
Here is my database:
Declare this object globally
Uri uri;
Set uri when user fetches the Image from the gallery
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
jimg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here sUrl will have downloadURL
private void uploadImage() {
try {
final StorageReference ref = storageReference.child( UUID.randomUUID().toString() );
//uploads the image
ref.putFile( uri ).addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener( new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final Uri downloadUrl = uri;
sUrl = downloadUrl.toString();
}
} ).addOnFailureListener( new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
} );
}
} );
}catch (Exception e){}
}

Item Doesn't seem to upload to Firebase Realtime Database while using Android [duplicate]

This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
Closed 3 years ago.
I am following a series of videos on youtube from the channel CodingInFlow. They are a bit Outdated, 2017 is long time ago. The Video Series is great and I followed up the 4th video no problem, except one deprecated function that was easy enough to resolve. The file uploads to the Firebase Storage, but it doesn't show up in the Real Time Database
Main Class
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
Button mButtonChooseImage;
Button mButtonUpload;
TextView mTextViewShowUploads;
EditText mEditTextFileName;
ImageView mImageView;
ProgressBar mProgressBar;
Uri mImageUri;
StorageReference mStorageRef;
DatabaseReference mDatabaseRef;
StorageTask mUploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonChooseImage = findViewById(R.id.button_choose_image);
mButtonUpload = findViewById(R.id.button_upload);
mTextViewShowUploads = findViewById(R.id.text_view_show_uploads);
mEditTextFileName = findViewById(R.id.edit_text_file_name);
mImageView = findViewById(R.id.image_view);
mProgressBar = findViewById(R.id.progress_bar);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(MainActivity.this, "Upload in Progress", Toast.LENGTH_SHORT).show();
} else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(mImageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Upload Successful", Toast.LENGTH_SHORT).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getStorage().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
//assert uploadId != null;
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
}
My question is, is it my mistake that I missed something (I followed the video exactly, and checked the code on the channel's website), or is it that the functionality shifted and something needs to be added?
The reason I ask is that the app works in the video, including the function that the checks for duplicate uploads, but in my reproduction, that function only works while the picture actually uploads, so there has been some shifting, but I don't even know where to start research, so I'm starting here.
This is how I did mine. This code saves the image to the storage and to the firebase realtime database under the child "profile image" as a link.
public class Registration3 extends AppCompatActivity {
Button elFin;
CircleImageView ProfileImage;
private DatabaseReference UsersRef;
private FirebaseAuth mAuth;
private StorageReference UserProfileImageRef;
String currentUserID;
final static int Gallery_Pick = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration3);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
elFin = findViewById(R.id.btn_dd);
ProfileImage = findViewById(R.id.profile_imageUp);
UsersRef = FirebaseDatabase.getInstance().getReference().child("DriversInformation").child(currentUserID);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profileimage");
ProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_Pick);
}
});
elFin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Registration3.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
Toast.makeText(Registration3.this, "Image Uplaoded", Toast.LENGTH_SHORT).show();
Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UsersRef.child("profileimage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent selfIntent = new Intent(Registration3.this, Registration3.class);
startActivity(selfIntent);
Toast.makeText(Registration3.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
} else {
String message = task.getException().getMessage();
Toast.makeText(Registration3.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
});
}
else {
Toast.makeText(Registration3.this, "Error: ", Toast.LENGTH_SHORT).show();
}
}
}
}

Trouble getting download Url of uploaded file in Android Firebase

I my trying to upload a profile picture to Firebase storage and then save it's download URL to database. The uploading works perfect but I'm facing problems with the download URL. I've tried almost everything on Stack Overflow. I'm sharing the relevant code.
private String user_Name, user_Email, user_Password, user_Age, user_Phone, imageUri;
Uri imagePath;
Selecting image
userProfilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*"); //Specify the type of intent
intent.setAction(Intent.ACTION_GET_CONTENT); //What action needs to be performed.
startActivityForResult(Intent.createChooser(intent, "Select Image"),
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) { //Here we get the result from startActivityForResult().
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data.getData() != null){
imagePath = data.getData(); //data.getData() holds the path of the file.
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath); //this converts the Uri to an image.
userProfilePic.setImageBitmap(bitmap);
imageTrue = 1;
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
uploading data
private void sendUserData (){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = firebaseDatabase.getReference("Users").child(firebaseAuth.getUid());
final StorageReference imageReference = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
//Here the root storage reference of our app storage is is "storageReference".
//.child(firebaseAuth.getUid()) creates a folder for every user. .child("images")
//creates another subfolder Images and the last child() function
//.child("Profile Pic") always gives the name of the file.
//User id/Images/profile_pic.png
//We can follow the same process for all other file types.
if(imageTrue==1){
UploadTask uploadTask = imageReference.putFile(imagePath); //Now we need to upload the file.
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "File Upload Failed", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUri = uri;
imageUri = downloadUri.toString();
}
});
Toast.makeText(getApplicationContext(), "File Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
});
}
UserProfile userProfile = new UserProfile(user_Name, user_Age, user_Email, user_Phone, imageUri);
myRef.setValue(userProfile);
Toast.makeText(getApplicationContext(), "User Data Sent.", Toast.LENGTH_SHORT).show();
}
Your code is right. You just need to make some correction inside your code in sendUserData() function. You will get your imageUrl inside onSuccess of your UploadTask
DatabaseReference myRef;
private void sendUserData (){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
myRef = firebaseDatabase.getReference("Users").child(firebaseAuth.getUid());
final StorageReference imageReference = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
//Here the root storage reference of our app storage is is "storageReference".
//.child(firebaseAuth.getUid()) creates a folder for every user. .child("images")
//creates another subfolder Images and the last child() function
//.child("Profile Pic") always gives the name of the file.
//User id/Images/profile_pic.png
//We can follow the same process for all other file types.
if(imageTrue==1){
UploadTask uploadTask = imageReference.putFile(imagePath); //Now we need to upload the file.
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "File Upload Failed", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUri = uri;
imageUri = downloadUri.toString();
saveUserDetails(imageUri); // Image uploaded
}
});
Toast.makeText(getApplicationContext(), "File Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
});
}else{
saveUserDetails(""); // Image not uploaded
}
}
Common function for saveUserDetails:
public void saveUserDetails(String imageUri){
UserProfile userProfile = new UserProfile(user_Name, user_Age, user_Email, user_Phone, imageUri);
myRef.setValue(userProfile);
Toast.makeText(getApplicationContext(), "User Data Sent.", Toast.LENGTH_SHORT).show();
}
according to Firebase official Documentation you can get download URl using UploadTask on addOnCompleteListener method.
UploadTask uploadTask =null;
final StorageReference ref = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic").child(imagePath);
uploadTask = ref.putFile(file);
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
saveUserDetails(uri);
} else {
// Handle failures
// ...
}
}
});
another alternative way , after uploading image successfully query and get your image url by using get downloadUrl.hope this may helps you!
private void getImageUrl(){
storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic").child(imagePath).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
saveUserDetails(uri);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
}

How to retreive and display profile pic Android firebase?

How to retreive and display profile pic of a the current user using uid? I already have the image connect to the users uid with uid, but not sure how to retreive and display.
This is how I upload it to Firebase Storage
mProfilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), GALLERY_INTENT);
}
});
I have the user click an imageview from there phone storage and upload that image with the current logged in users uid.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK && data != null && data.getData() != null){
mainImageURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), mainImageURI);
mProfilePic.setImageBitmap(bitmap);
final ProgressDialog proDialog = new ProgressDialog(HomeActivity.this);
proDialog.setTitle("Uploading...");
proDialog.show();
String userUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
UploadTask uploadTask = FirebaseStorage.getInstance().getReference().child("newFolder").child(userUid).putFile(mainImageURI);
uploadTask
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
final StorageReference mRef = mStorage.child("Photos").child(mainImageURI.getLastPathSegment());
mRef.putFile(mainImageURI).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
proDialog.dismiss();
Toast.makeText(HomeActivity.this, "Uploaded", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
proDialog.dismiss();
Toast.makeText(HomeActivity.this, "Upload Failed "+e.getMessage(), Toast.LENGTH_LONG).show();
}
})
} catch(IOException e) {
e.printStackTrace();
}
}
}
Maintain a database where you can save image url against the uid. Then retrieve your profil pic using that url from database
store the image url in a document with the uid and all other attribute and the you can retrieve the image using Glide library
https://github.com/bumptech/glide

Categories