1

What I'm trying to do is pretty simple: Pick an image from my phone (anywhere) and convert it to a File. My final goal is to use this upload this file into my DB (a thing that I already succeed with a picture that I took from the camera).

My situation is: when I'm trying to create my file from the path given by the Uri. It doesn't work. I have read from some topics on SO and some other websites that sometimes it's impossible to create a file from the Uri's path like on these websites :

https://freakycoder.com/android-notes-73-how-to-get-real-path-from-uri-2f78320987f5

https://www.dev2qa.com/how-to-get-real-file-path-from-android-uri/

Also tried that way : Android - Get file with path

but still doesn't work.

My current code : How I'm picking up the picture :

public void exportPicture() {

        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(intent, READ_REQUEST_CODE);
    }

how my Uri is filling :

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                photoURI = data.getData();
                Log.d("URI", "Uri:" + photoURI.toString());
            }
        }
    }

how I'm trying to create the file :

if (photoURI != null) {
  File file = new File (photoURI.getPath());
}

I got the following error :

java.io.FileNotFoundException: /external/file/186142 (No such file or directory)

I'm under Oreo.

EDIT : Answer found here : stackoverflow.com/a/52095352

Itoun
  • 3,713
  • 5
  • 27
  • 47
  • A `Uri` is not a file. It might point to a file sometimes, but it may very well not. Use `getContentResolver().openInputStream()` with the returned `Uri`, and use basic stream and file I/O to save it where you want it. – Mike M. Jan 26 '19 at 08:23
  • I already have seen something like that on this post: https://stackoverflow.com/a/45808621/7937498 But I didn't get how to write the final file after use openInputStream @MikeM. – Itoun Jan 26 '19 at 08:26
  • 1
    Yeah, that's rather terse. There's a pretty simple, straightforward example here: https://stackoverflow.com/a/45520771. And a few others I have in my list for when this question comes up: https://stackoverflow.com/q/13133579, https://stackoverflow.com/q/21960650, https://stackoverflow.com/a/52095352. – Mike M. Jan 26 '19 at 08:32
  • 1
    I used this answer stackoverflow.com/a/52095352. @MikeM. Thank you so much it's working as well !! – Itoun Jan 26 '19 at 08:57

0 Answers0