Save image download address in Firebase Storage in Firebase DataBase

1

I build an app where in an activity you can choose a photo upload it and then upload your other information such as age name etc. My code starts asking you to select a photo of where you want and then you cut it then upload to the Firebase Storage, until here there are no problems so much the image as the data upload correctly. the problem is when saving the url of downloading the photo in the database of firebase datas and then ask for it and show the profile photo. This is what is saved:

I have the following code Activity (RegisterDataActivity.java):

final static int Gallery_Pick = 1;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
private StorageReference UserProfileImageRef;
String currentUserID;

@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 ){

        Uri ImageUri = data.getData();
        CropImage.activity(ImageUri)
                .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){
            loadingBar.setTitle("Cargando imagen");
            loadingBar.setMessage("Por favor espere, mientras actualizamos su foto de perfil.");
            loadingBar.show();
            loadingBar.setCanceledOnTouchOutside(true);
            final Uri resultUri = result.getUri();
            final 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(RegisterDataActivity.this,"Foto de perfil guardada", Toast.LENGTH_SHORT).show();
                        final String downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
                        UsersRef.child("profileimage").setValue(downloadUrl)
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if (task.isSuccessful()){
                                            ReintentRegisterData();
                                            Toast.makeText(RegisterDataActivity.this, "Foto de perfil guardada",Toast.LENGTH_SHORT).show();
                                            loadingBar.dismiss();
                                        }else{
                                            String message = task.getException().getMessage();
                                            Toast.makeText(RegisterDataActivity.this, "Error:"+ message,Toast.LENGTH_SHORT).show();
                                            loadingBar.dismiss();
                                        }
                                    }
                                });
                    }
                }
            });

        }else{
            Toast.makeText(RegisterDataActivity.this, "Error: La imagen no se pudo recortar intentalo otra vez.",Toast.LENGTH_SHORT).show();
            loadingBar.dismiss();
        }
    }


}

 private void inicializaUI(){

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();
    UsersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
    UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
    //Country Picker
    countryPicker = new CountryPicker.Builder().with(this)
            .listener(this)
            .build();

}
    
asked by Riddick 16.10.2018 в 22:33
source

1 answer

0

You should do it in the following way using Task

  final StorageReference filePath = UserProfileImageRef.child(currentUserID+".jpg");
                filePath.putFile(resultUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
        @Override
        public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
           //Preguntamos si el task de subir la imagen fue exitoso, si lo es retornamos la url de descarga del archivo subido , sino lanzamos una exception.
              if (!task.isSuccessful()) {
                throw task.getException();
            }

            return filePath.getDownloadUrl();
        }.addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    //Luego si se utiliza addOnCompleteListener para obtener ese enlace
                      if (task.isSuccessful()) {
                       //Obtenemos el uri del enlace
                        Uri downloadUrl = task.getResult();
                        Log.d(TAG, "onComplete: Enlace de descarga" + 
                        downloadUri.toString() );

                UsersRef.child("profileimage").setValue(downloadUrl.toString())
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if (task.isSuccessful()){
                                            ReintentRegisterData();
                                            Toast.makeText(RegisterDataActivity.this, "Foto de perfil guardada",Toast.LENGTH_SHORT).show();
                                            loadingBar.dismiss();
                                        }else{
                                            String message = task.getException().getMessage();
                                            Toast.makeText(RegisterDataActivity.this, "Error:"+ message,Toast.LENGTH_SHORT).show();
                                            loadingBar.dismiss();
                                        }
                                    }
                                });


                    } else {
                                          Toast.makeText(mContext, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();

                    }
                }
            });

This way should work, what we do is use Task to return the status of the operation before getting the download link, and then, when that return gave us the download link of that file, we can just do the logic to upload that link to our Database.

For more info I leave the documentation

answered by 18.10.2018 / 15:05
source