user15537898
user15537898

Reputation:

Problem in download Imageuri in Firebase Storage Android

I'm uploading images from my app and storing the download URL in a model class but after I see the URL I copied it and paste the link but it didn't open up the image.

Here is the Firebase Realtime Database image enter image description here

Here is the Firebase Storage enter image description here

and here what it should be https://firebasestorage.googleapis.com/v0/b/myapp-not-final.appspot.com/o/uploads%2F1618234721167.jpg?alt=media&token=fcac1404-87ce-4c7d-ae5f-a1ec7074bf04

Java Files

Upload_Fragment.java

public class Upload_Fragment extends Fragment {
    private static final int PICK_IMAGE_REQUEST = 10;
    private ImageView uploadImageView;
    private Uri mImageUri;
    private StorageReference storageReference;
    private DatabaseReference databaseReference;
    private StorageTask mUploadTask;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_upload, container, false);
        Button chooseImageButton = view.findViewById(R.id.upload_image_button);
        Button uploadImageButton = view.findViewById(R.id.done_button);
        uploadImageView = view.findViewById(R.id.upload_image_view);
        FirebaseStorage storage = FirebaseStorage.getInstance();
        storageReference = storage.getReference("uploads");
        databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
        chooseImageButton.setOnClickListener(v -> openFileChooser());
        uploadImageButton.setOnClickListener(v -> {
            if (mUploadTask != null && mUploadTask.isInProgress()) {
                Toast.makeText(getActivity(), "Upload in Progress", Toast.LENGTH_SHORT).show();

            } else {
                uploadToFirebase(mImageUri);
            }


        });

        return view;
    }

    private void openFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    public 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(uploadImageView);

        }
    }

    private String getFileExtension(Uri uri) {

        ContentResolver contentResolver = Objects.requireNonNull(getActivity()).getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        return mime.getExtensionFromMimeType(contentResolver.getType(uri));
    }

    private void uploadToFirebase(Uri mImageUri) {
        if (mImageUri != null) {
            final ProgressDialog progressDialog = new ProgressDialog(getActivity());
            progressDialog.setTitle("Uploading...");
            progressDialog.show();

            StorageReference reference = storageReference.child(System.currentTimeMillis()
                    + "." + getFileExtension(mImageUri));
            reference.putFile(mImageUri)
                    .addOnSuccessListener(taskSnapshot -> {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(), "Saved Succesfully", Toast.LENGTH_SHORT).show();
                        reference.getDownloadUrl()
                                .addOnSuccessListener(uri -> {
                                    Upload upload = new Upload(mImageUri.toString());
                                    String uploadId = databaseReference.push().getKey();
                                    databaseReference.child(uploadId).setValue(upload);
                                });
                    })
                    .addOnProgressListener(snapshot -> {
                        double progress = (100.0 * snapshot.getBytesTransferred() / snapshot
                                .getTotalByteCount());
                        progressDialog.setMessage("Uploaded " + (int) progress + "%");
                    })
                    .addOnFailureListener(e -> {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(), "Error Ocurred" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });


        }
    }
}

Upload.java // This is the model class

public class Upload {
    private String mImageUrl;


    public Upload() {

    }

    public Upload(String imageUrl) {
        mImageUrl = imageUrl;
    }

    public String getmImageUrl() {
        return mImageUrl;
    }

    public void setmImageUrl(String mImageUrl) {
        this.mImageUrl = mImageUrl;
    }
}

Upvotes: 0

Views: 433

Answers (2)

Purvesh Dodiya
Purvesh Dodiya

Reputation: 590

in uploadToFirebase method inside

reference.getDownloadUrl().addOnSuccessListener(uri -> {.....

instead of mImageUri.toString() put uri.toString() as per bellow.So you will get actual url and will solve your problem.

private void uploadToFirebase(Uri mImageUri) {
        if (mImageUri != null) {
            final ProgressDialog progressDialog = new ProgressDialog(getActivity());
            progressDialog.setTitle("Uploading...");
            progressDialog.show();

            StorageReference reference = storageReference.child(System.currentTimeMillis()
                    + "." + getFileExtension(mImageUri));
            reference.putFile(mImageUri)
                    .addOnSuccessListener(taskSnapshot -> {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(), "Saved Succesfully", Toast.LENGTH_SHORT).show();
                        reference.getDownloadUrl()
                                .addOnSuccessListener(uri -> {
                                    Upload upload = new Upload(uri.toString());
                                    String uploadId = databaseReference.push().getKey();
                                    databaseReference.child(uploadId).setValue(upload);
                                });
                    })
                    .addOnProgressListener(snapshot -> {
                        double progress = (100.0 * snapshot.getBytesTransferred() / snapshot
                                .getTotalByteCount());
                        progressDialog.setMessage("Uploaded " + (int) progress + "%");
                    })
                    .addOnFailureListener(e -> {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(), "Error Ocurred" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });


        }
    }

Upvotes: 1

Alex Mamo
Alex Mamo

Reputation: 139029

In your database schema, your "mImageUrl" property holds a URL similar to this:

content://com.android.externalstorage.documents...

As you probably see, those URLs are pointing to some files that are located locally on the external storage. So you cannot use such URLs and expect to read data from Firebase Storage. To check the URL of an image in the Firebase Console, please see on the right-hand side a section called "File location". If you click on the token you'll get a copy of the URL of the image that looks similar to this:

https://firebasestorage.googleapis.com/v0/b/myapp-not-final.appspot.com/...

This means that this is the correct URL that should be stored in the database and not the local one. To get the download URL please check my answer from the following post:

Once you have the correct URL, add it to Firestore so it can be later used.

Upvotes: 0

Related Questions