0

I'm trying to retrieve an image from the gallery and get its absolute path in order to save it to the local database. Below is the code to initialize the intent to open the gallery.

fabChooseImage.setOnClickListener(view -> {
    Intent i = new Intent();
    i.setType("image/*");
    i.setAction(Intent.ACTION_GET_CONTENT);
        
    startActivityForResult(Intent.createChooser(i, "Select Picture"), SELECT_PICTURE);
});

Then I handle the result as such:

Uri imgUri = data.getData();
if (imgUri != null) {
    ivImage.setImageURI(imgUri);

    File myFile = new File((imgUri.getPath()));
    mSelectedImagePath = myFile.getAbsolutePath();

    Toast.makeText(AddPostActivity.this, mSelectedImagePath, Toast.LENGTH_LONG).show();
}

However, this does not seem to give the absolute path and instead returns

/document/image:5632

When in fact I want the absolute path of:

Phone/files/avatars/sample.jpg

SS-Salt
  • 139
  • 7
  • "to save it to the local database" -- you do not need a filesystem path to copy the content. Use `ContentResolver` and `openInputStream()` to get an `InputStream` on the content, which you can use to make a copy. Also note that storing images in SQLite on Android is not a good idea, owing to some limitations in how Android's SQLite API handles large query results. – CommonsWare Sep 16 '21 at 14:58
  • I am trying to save only the file path to the database, and display the image using said path on runtime. – SS-Salt Sep 16 '21 at 15:06
  • 1
    There is no file path that you can use. Use `ACTION_OPEN_DOCUMENT` instead of `ACTION_GET_CONTENT`. Then, call `takePersistableUriPermission()` on a `ContentResolver`, passing in the `Uri`. Now, you can persist the `Uri` in your database, for use with Glide, Picasso, or your favorite image-loading library. – CommonsWare Sep 16 '21 at 15:30

0 Answers0