I am uploading a picture to Firebase storage in my app. It uploads fine and can be viewed in firebase storage online. When i'm trying to fetch it and show it in an image view, it does not show up in the image view instead the image view vanishes as well. I have tried this with Piccaso and glide and nothing is working. The code is attached below
Uploading Code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
profile_image = findViewById(R.id.profileimage);
profile_image.setImageBitmap(bitmap);
imageRef=storageReference.child(userID);
imageRef.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//if the upload is successful
//hiding the progress dialog
//and displaying a success toast
//dismissDialog();
profilePicUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
//if the upload is not successful
//hiding the progress dialog
// dismissDialog();
//and displaying error message
Toast.makeText(profile.this, exception.getCause().getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
Download and loading into image view Code:
fbstorage=FirebaseStorage.getInstance();
storageReference=fbstorage.getReference();
imageRef=storageReference.child(userID);
final String h=imageRef.getDownloadUrl().toString();
storageReference.child(userID).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Toast.makeText(profile.this, "hello", Toast.LENGTH_SHORT).show();
Picasso.with(profile.this).load(h).into(profile_image);
}
});
try it with glide .. this code works fine with me
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("folderName"+"/"+thePicName);
Glide.with(context.getApplicationContext())
.using(new FirebaseImageLoader())
.load(storageReference)
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.priority(Priority.IMMEDIATE)
.into(new BitmapImageViewTarget(pic) {
#Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(context.getResources(),
Bitmap.createScaledBitmap(resource, 150, 150, false));
drawable.setCircular(false);
pic.setImageDrawable(drawable);
}
});
Related
I am trying to use the following code to have a user select an image, and after the image is selected, it is automatically uploaded to my Firebase storage. I initialized the variable storageReference in the OnCreate function
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent, "Select Image"), 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#SuppressLint("LongLogTag")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// If the image is uploaded properly and the resultcode is OK
// The imagePreview is updated and the image is uploaded
if(requestCode == 1 || requestCode == 2) {
if (resultCode == Activity.RESULT_OK && data != null && data.getData() == null) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(requireContext().getContentResolver(), filePath);
imagePreview.setImageBitmap(bitmap);
uploadImage();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void uploadImage()
{
if (filePath != null) {
// Code for showing progressDialog while uploading
ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setTitle("Uploading...");
progressDialog.show();
// Defining the child of storageReference
StorageReference ref = storageReference.child(mAuth.getCurrentUser().toString());
// adding listeners on upload
// or failure of image
ref.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Image uploaded successfully
// Dismiss dialog
progressDialog.dismiss();
Toast.makeText(getActivity(), "Image Uploaded!!", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Error, Image not uploaded
progressDialog.dismiss();
Toast.makeText(getContext(),"Failed " + e.getMessage(),Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
// Progress Listener for loading
// percentage on the dialog box
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int)progress + "%");
}
});
}
}
My guess is that the uploadImage function is not being called but I am not sure why.
I figured it out, the issue was with this line
if (resultCode == Activity.RESULT_OK && data != null && data.getData() == null)
data.getData() == null
should be:
data.getData() != null
I want to add a photo from the gallery using picasso to imageView, but it is not displayed, photos from the Internet are displayed and those that were photographed from the camera are not
enter code here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_PICK_GALLERY_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
image_uri = data.getData();
Picasso.with(this)
.load(image_uri)
.error(R.drawable.defaultimage)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
image.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
image.setImageDrawable(errorDrawable);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
} else {
//startActivity(new Intent(Main2Activity.this, MyActivity.class));
}
}
In High API level devices. you need to add this line in Manifest Application tag
android:requestLegacyExternalStorage="true"
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
}
});
}
}
});
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 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