How do I download a file that is in Storage by my app (Adnroid Studio)

Asked

Viewed 31 times

0

I took a look at the documentation provided by Firebase and still did not understand how to download a file that is in Storage by my app using Android Studio, someone can help me?

1 answer

1

Salve @Developd,

1 - First thing to do is select the image you want to upload.

@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fb_upload_profile_image:
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(Intent.createChooser(i, "Selecione uma imagem"), 1000);
                break;
        }
    }

2 - After the Intent was triggered, we need to get the image selected by the user in order to send it to Firebase Storage

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_CANCELED) {
            if (requestCode == 1000) {

                Uri selectedImage = data.getData();
                File f = new File(String.valueOf(selectedImage));
                Bitmap bitmap = null;
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);
                } catch (IOException e) {
                    e.printStackTrace();
                }


                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] data = baos.toByteArray();

                mStorageRef.child("profile_imgs/".concat(f.getName()))
               .putBytes(data).addOnCompleteListener(new  OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                     if (task.isSuccessful()) {
                         String url = task.getResult()
                        .getDownloadUrl()
                        .toString();
                        /* Essa é a url de onde a imagem fica armazenada. É comum salvá-la no Firebase Database para uso posterior*/
                        Toast.makeText(this, "Foto atualizada com êxito", Toast.LENGTH_LONG)
            .show();
                     } else {
                        Toast.makeText(this, "Não foi possível atualizar a foto de perfil", Toast.LENGTH_LONG).show();
                     }
                 }
               });
            }
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.