Replacing the deprecated taskSnapshot.getDownloadUrl().toString(); - android

I am following an android tutorial and I have been stuck on the deprecated method. I am unable to get the download url to enable me show the image in an ImageView
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICTURE_RESULT && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
StorageReference ref = FirebaseUtil.mStorageRef.child(imageUri.getLastPathSegment());
ref.putFile(imageUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String url = taskSnapshot.getDownloadUrl().toString();
String pictureName = taskSnapshot.getStorage().getPath();
deal.setImageUrl(url);
How can I modify the line "String url = taskSnapshot.getDownloadUrl().toString();" so that I can be able to get the download link?

getDownloadUrl() is deprecated so you need to use Task and check isComplete() like below to see if it is completed
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICTURE_RESULT && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
StorageReference ref = FirebaseUtil.mStorageRef.child(imageUri.getLastPathSegment());
ref.putFile(imageUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uri = taskSnapshot.getStorage().getDownloadUrl();
while(!uri.isComplete());
Uri url = uri.getResult();
Log.i(TAG, url.toString());
deal.setImageUrl(url.toString());

Try this
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()

Try this
StorageReference imageRef = FirebaseUtil.mStorageRef.child(imageUri.getLastPathSegment());
UploadTask uploadTask = imageRef.putFile(imageUri);
uploadTask.continueWithTask(task -> {
if (!task.isSuccessful()) {
if (task.getException() != null)
throw task.getException();
}
return imageRef.getDownloadUrl();
}).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult()
} else {
if (task.getException() != null)
task.getException().printStackTrace();
}
});

Related

How to crop and upload my image to firebase?

Here I am using imagecropper dependency to crop and upload it to Firebase.
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
Uri image_uri = data.getData();
CropImage.activity(data.getData())
.setGuidelines(CropImageView.Guidelines.ON)
.start(getActivity());
//Updateprofilephoto(image_uri);
} else if (requestCode == IMAGE_PICK_CAMERA_CODE) {
//profileIv.setImageURI(image_uri);
CropImage.activity(data.getData())
.setGuidelines(CropImageView.Guidelines.ON)
.start(getActivity());
//uploadProfilePhoto(resulturi);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
Updateprofilephoto(resultUri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
My code works until this. I can crop the image by choosing an image from my gallery. But by using the following method I cannot upload my cropped image to the Firebase. The original image is uploaded to the Firebase. Not the cropped one. How can I solve that issue?
The code follows:
private void Updateprofilephoto(Uri resulturi) {
progressDialog.setMessage("Updating Account Info...");
progressDialog.setProgressStyle(progressDialog.STYLE_SPINNER);
progressDialog.show();
String filePathAndName = "profile_image/" + "" + firebaseAuth.getUid();
StorageReference storageReference = FirebaseStorage.getInstance().getReference(filePathAndName);
storageReference.putFile(resulturi)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
Uri downloadImageUri = uriTask.getResult();
if (uriTask.isSuccessful()) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("profileImage", "" + downloadImageUri);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child(firebaseAuth.getUid()).updateChildren(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Profile Picture is updated...", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}

Parsing Uri with CircleImageView

How do I Parse uri with de.hdodenhof.circleimageview.CircleImageView?
My code
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
final Uri uri = data.getData();
StorageReference path = mStoragereference.child("Photos").child(uri.getLastPathSegment());
path.putFile(uri).addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setPhotoUri(Uri.parse(userPhoto))
.build();
if (userPhoto == null) {
Toast.makeText(EditInfo.this, "Error updating image",
Toast.LENGTH_SHORT).show();
}
Thanks for your response!
Since CircleImageView is a subclass of ImageView it inherits most of its properties/methods from ImageView.
Unfortunately it seems that ImageView doesn't expose its source URI, so you'll have to keep the URI that you pass into the CircleImageView around.

Image is failed to upload in Firebase storage

Can you please help me, I am trying to upload an image in FirebaseStorage.
But it fails.
My Button click Method
public void uploadImage(View view){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,GALLERY_INTENT);
}
And here is onActivityResult()
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
progressDialog.setMessage("Uploading");
progressDialog.show();
if(requestCode ==GALLERY_INTENT){
final Uri uri = data.getData();
StorageReference filepath = storageReference.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(),"Uploaded Successfully",Toast.LENGTH_LONG).show();
// profileImage.setImageURI(uri);
progressDialog.dismiss();
}
});
}
}
What's wrong with this code?
Try this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("resultCode: ", resultCode + " RequestCode: " + requestCode);
if (resultCode == getActivity().RESULT_OK) {
sendImageToFireBase(data.getData());
}
}
private void saveImageToFireBase(Uri pathUri) {
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Photos");
StorageReference photoRef = storageReference.child(pathUri.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(pathUri).addOnSuccessListener(getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
}
});
}

App crashes when trying to upload to Firebase

When I try to upload to Firebase my app is crashing with the following error.
I have an 'upload' button that is being used to invoke the camera. Upon clicking it, the image is not uploaded to Firebase.
My code:
private Button mUploadBtn;
private ImageView mImageView;
private static final int CAMERA_REQUEST_CODE = 1;
private StorageReference mStorage;
Uri photoURI;
private ProgressDialog mProgressDialog;
private static final int GALLERY_INTENT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mUploadBtn = (Button) findViewById(R.id.upload);
mImageView = (ImageView) findViewById(R.id.imageView);
mProgressDialog = new ProgressDialog(this);
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
mProgressDialog.setMessage("Uplaoding");
mProgressDialog.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photos").child("file");
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this,"Done",Toast.LENGTH_LONG).show();
}
});
}
}
It looks like you're not working with the camera intent correctly. The code you show is expecting that the intent returned by the camera app contains a Uri to the captured image via its getData() method. That's not the way it works.
I recommend you follow this tutorial instead to work with the camera.
override this method
and do the following steps
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK)
{
Uri uri = data.getData();
StorageReference image_path = storageReference.child("Camera Photos").child(uri.getLastPathSegment());
image_path.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
}
});
}
}

Image-Crop-Activity doesn't send Image-Uri to receiving Activity (Android-Image-Cropper)

I am trying to crop an image (which I've chosen from the gallery or taken from my camera) and pass it to another activity which should upload the image to my firebase storage.
At first (without the image cropping) everything went well. I was able to pass and upload the image...but after adding the image-crop-code to my onActivityResult it just closes the imageCropActivity after pressing 'crop' and jumps back to my MainActivity.
I've tried but I really cannnot figure out why it does that. Maybe I'm missing something out. Any ideas?
For the image cropping I'm using this libary: https://github.com/ArthurHub/Android-Image-Cropper
Main Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mImageUri_gallery = data.getData();
mImageUri_camera = data.getData();
if (requestCode == 100 && resultCode == RESULT_OK) {
CropImage.activity(mImageUri_gallery)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUriGallery = result.getUri();
Intent intentGallery = new Intent(MainActivity.this, ImagePostActivity.class);
intentGallery.putExtra("image-uri", resultUriGallery.toString());
startActivity(intentGallery);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
} else if (resultCode != RESULT_CANCELED && data != null) {
if (requestCode == 200 && resultCode == RESULT_OK) {
CropImage.activity(mImageUri_camera)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUriCamera = result.getUri();
Intent intentCamera = new Intent(MainActivity.this, ImagePostActivity.class);
intentCamera.putExtra("image-uri", resultUriCamera.toString());
startActivity(intentCamera);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
}
ImagePostActivity
public class ImagePostActivity extends AppCompatActivity {
public static TextView txt_btn_post;
public static EditText mPostTitle;
public static ImageView imagePostPreview;
private StorageReference mStorage;
private DatabaseReference mDatabase;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_post);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mStorage = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Test_Stream_Uploads");
mProgress = new ProgressDialog(this);
// mPostTitle = (EditText) findViewById(R.id.mPostTitle);
imagePostPreview = (ImageView) findViewById(R.id.imagePostPreview);
Intent intent = getIntent();
mImageUri_gallery = Uri.parse(intent.getStringExtra("image-uri"));
imagePostPreview.setImageURI(mImageUri_gallery);
mImageUri_camera = Uri.parse(intent.getStringExtra("image-uri"));
imagePostPreview.setImageURI(mImageUri_camera);
txt_btn_post = (TextView) findViewById(R.id.txt_btn_post);
txt_btn_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startPosting();
}
});
}
private void startPosting() {
mProgress.setMessage("Bild wird hochgeladen...");
mProgress.show();
if (mImageUri_gallery != null) {
StorageReference filepath = mStorage.child("Stream_Image").child(mImageUri_gallery.getLastPathSegment());
filepath.putFile(mImageUri_gallery).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Intent intent = new Intent(getBaseContext(), MainActivity.class);
DatabaseReference newPost = mDatabase.push();
newPost.child("image").setValue(downloadUrl.toString());
mProgress.dismiss();
startActivity(intent);
}
});
}
}
}
I'm also actively using this tool and I actually didn't really got into your code but I can offer you an example of how it works for me. If you look into it you can easily follow and get the idea. It works for the images you take from the gallery.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(144,81)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
ib_image.setImageURI(resultUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
If you want to apply this to the image you just took from the camera, you'll need to create your own uri, it's a bit long way but it's explained in the Android Documentation:(https://developer.android.com/training/camera/photobasics.html#TaskPhotoView), this I've explained in a discussion here: Image capture with camera & upload to Firebase (Uri in onActivityResult() is null)

Categories

Resources