1

I need to develop functionality to load an image from the gallery and upload it to the server.

The format that is sent to the server is File. When I select a picture from the phone, I get the Uri content.

The old way that was used to convert Uri content to full image path is:

fun getFilePathFromUri(context: Context, uri: Uri) : String? {
    var realPath: String? = null
    try {
        val column = MediaStore.Images.Media.DATA
        val projection = arrayOf(column)
        context.contentResolver.query(
            uri,
            projection,
            null,
            null,
            null
        )?.use { cursor ->
            if (cursor.count > 0) {
                if (cursor.moveToFirst()) {
                    val columnIndex = cursor.getColumnIndexOrThrow(column)
                    realPath = cursor.getString(columnIndex)
                }
            }
            cursor.close()
        }
    } catch (e: Exception) {
        Timber.e(e)
    }

    return realPath
}

Google has announced that now MediaStore.Images.Media.DATA -> 'DATA: String' is deprecated. How is this done now? How to get the full path?

Michael
  • 73
  • 7
  • Refer to this: https://stackoverflow.com/a/65835084/14884388 – Hascher Aug 19 '21 at 18:30
  • 1
    "The format that is sent to the server is File" -- this is a bug. You need to fix this bug. For example, if you are using OkHttp or something layered atop of it (like Retrofit), there are [multiple recipes for implementing a `RequestBody` that can use a `Uri` directly](https://stackoverflow.com/questions/56308559/create-a-file-from-a-photo-uri-on-android). – CommonsWare Aug 19 '21 at 18:33
  • @CommonsWare Okay, thanks, I looked, it seems ok to me. I have another dilemma. So far when I was taking pictures, I was working by creating a temporary file and using FileProvider. Uri such images start with file://, not content://. Content Uri is required for this method you sent. How do I overcome this problem? – Michael Aug 20 '21 at 10:04
  • "Uri such images start with file://, not content://" -- the `getUriForFile()` method on `FileProvider` does not create a `file://` `Uri`. It creates a `content://` `Uri`. – CommonsWare Aug 20 '21 at 10:34
  • @CommonsWare Yes, they are right. Sorry. The problem though is in the 'com.theartofdev.edmodo: android-image-cropper: 2.8. +' Library because I'm doing image cropping. As a result, I always get the file://. I need to adjust that somehow – Michael Aug 20 '21 at 10:40
  • There are [many image cropping libraries](https://android-arsenal.com/tag/45?sort=created). Perhaps another one fits your scenario better. – CommonsWare Aug 20 '21 at 10:41
  • Yes, I just need to find which one exactly returns the content URI – Michael Aug 20 '21 at 10:44
  • If you already know one, send it. And thank you so much for this above! – Michael Aug 20 '21 at 10:45

0 Answers0